有一個搜索組件,當有效負載重新定向到結果組件時。希望結果組件使用React Router v4 Redirect來顯示搜索的傳遞狀態。我在這裏從Docs的假設是,使用state: { referrer: currentLocation }
可以傳遞一個對象。React路由器v4重定向傳遞狀態從搜索到結果
搜索
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>
);
}
}
結果
除非我不讀這個正確,這個問題似乎是,當重定向發生沒有什麼是傳遞給結果組件。
如果輸入值並且成功重定向發生搜索狀態返回Object {searchValue: "", results: Array(1)}
但是,根據初始狀態設置,搜索結果狀態將返回Object {results: Array(0)}
或undefined
。
在結果上也嘗試過不同的組件生命週期,但無法以任何方式獲取任何傳遞的數據。我的想法可能是可能能夠獲得一些通過數據,並可以通過這些手段設置狀態。