【发布时间】:2017-06-12 23:30:27
【问题描述】:
有一个搜索组件,当有效负载返回时,它会重定向到结果组件。希望该结果组件使用React Router v4 Redirect 显示通过的搜索状态。我在文档中的假设是使用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>
);
}
}
结果
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>
);
}
}
除非我没有正确阅读,否则问题似乎是当重定向发生时,没有任何东西被传递到结果组件中。
如果输入值并成功重定向,则会发生搜索状态返回 Object {searchValue: "", results: Array(1)} 但是搜索结果状态返回 Object {results: Array(0)} 或 undefined,具体取决于初始状态设置。
还在结果中尝试了不同的组件生命周期,但无法以这种方式获取任何传递的数据。我认为componentWillRecieveProps(nextProps, nextState){} 可能能够获取一些传递的数据,并且可以通过这些方式设置状态。
【问题讨论】:
标签: javascript reactjs react-router