我是新来响应JS的人,并且发现很难通过响应路由器 this.props.history.push()方法传递值。 这是我的反应文件:
App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Clock from './Clock.js';
import NameForm from './NameForm.js';
import Home from './pages/Home/Home.js';
import SearchResultPage from './pages/search/SearchResularPage.js';
import { Switch, Route, BrowserRouter } from 'react-router-dom'
class App extends Component {
constructor() {
super();
this.state = {
name: 'siva',
searchText: 'sivaprakash'
};
//this.handleClick = this.handleClick.bind(this);
}
render() {
return (
<div className="shopping-list">
<BrowserRouter>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/SearchResultPage' render={() =>
<SearchResultPage SearchText={this.state.searchText} />
} />
</Switch>
</BrowserRouter>
</div>
);
}
}
export default App;
Home.js
import React, { Component } from 'react';
import Header from './../../Header/Header.js'
import './Home.css';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date(),
searchText : 'fdsfsfs'
};
}
handleOnClick = () => {
// some action...
// then redirect
alert("yes");
this.props.history.push({
pathname: '/SearchResultPage',
state: {
hello:"okay",
}
});
}
render() {
return (
<div>
<button onClick={this.handleOnClick}>Pass value</button>
</div>
);
}
}
export default Home;
SearchResularPage.js
import React, { Component } from 'react';
class SearchResultPage extends React.Component {
constructor(props) {
super(props);
this.state = {
searchValue :this.props.SearchText,
pramvalue : props.location.state
};
}
render() {
return (
<div>
{this.state.searchValue}
{this.state.pramvalue}
</div>
);
}
}
export default SearchResultPage;
预期结果。
通过单击Home.js中的[传递值]按钮将重定向到名为 SearchResultPage 的下一页,并应在SearchResultPage页面中显示“确定” 。 请帮助我解决此问题。
答案 0 :(得分:1)
要解决此问题,可以在 SearchResularPage 页面中像这样使用withRouter
:
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom'
class SearchResultPage extends React.Component {
constructor(props) {
super(props);
this.state = {
searchValue :'',
paramvalue : ''
};
}
componentDidMount(){
this.setState({
searchValue: this.props.SearchText,
paramValue: this.props.location.state
})
}
render() {
return (
<div>
{this.state.searchValue}
{this.state.paramValue ? this.state.paramValue.hello : ''}
</div>
);
}
}
export default withRouter(SearchResultPage);
希望它会有所帮助:)