Ful*_*rid 5 javascript reactjs react-router
有一个Search组件,当有效负载返回时重定向到Results组件.希望结果组件使用React Router v4 Redirect显示已通过的搜索状态.我在Docs中的假设是state: { referrer: currentLocation }可以传递使用对象.
搜索
export default class Search extends Component{
constructor(props){
super(props);
this.state = {
searchValue: '',
results:[]
}
this.handleKeyPress = this.handleKeyPress.bind(this);
}
handleKeyPress = (e) => {
let searchParam = e.target.value;
if (e.key === 'Enter'){
axios
.get(URL+searchParam)
.then((response) => {
this.setState({results: response.data});
});
}
};
render(){
return(
<div>
<input
ref="search"
type="text"
placeholder="Search"
onKeyPress={this.handleKeyPress.bind(this)}
/>
{this.state.results.length > 0 &&
<Redirect to={{
pathname: '/results',
state: { results: this.state.results }
}} />
}
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
结果
export default class Results extends Component{
constructor(props){
super(props);
this.state = {
results:[] // <<<<<< Not sure if this needs set
}
}
render(){
console.log('SEARCH RESULTS STATE', this.state); // <<<< this either returns undefined or just an empty array depending if initial state is set
return(
<div>
<h1>Search Results</h1>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
除非我没有正确地读到这个,否则问题似乎是当重定向发生时,没有任何东西被传递到Results组件中.
如果输入值并且成功则重定向发生搜索状态返回Object {searchValue: "", results: Array(1)}但是搜索结果状态返回Object {results: Array(0)}或undefined取决于初始状态设置.
还在结果上尝试了不同的组件生命周期,但无法以这种方式获取任何传递的数据.我的想法componentWillRecieveProps(nextProps, nextState){}可能是可以获得一些传递的数据,并可以通过这些方式设置状态.
在您的主类组件的render()方法的开头,您必须编写代码,例如:
if (isLoggedIn){
return <Redirect to={{
pathname: '/anyPath',
state: { stateName: this.state.anyState}
}} />;
}
Run Code Online (Sandbox Code Playgroud)
并且在与Route相关联的组件中,/anyPath您必须提取传递的状态调用this.props.location.state.stateName.在您的确切情况下,您应该this.props.location.state.results在结果类中调用.您可以从Results类中删除构造函数方法.
isLoggedIn可能是另一个状态,您可以在主要组件的构造函数Method中首先设置为false.isLoggedIn如果用户单击按钮,则可以设置为true,这样您就可以将应用程序重定向到具有首选状态的另一个Route.
| 归档时间: |
|
| 查看次数: |
8068 次 |
| 最近记录: |