React-router history.listen not running in componentWillMoun



>我正在尝试制作一个 SearchResults 组件,该组件根据查询字符串中的内容显示搜索结果,该字符串由 SearchForm 组件更新。这里建议我使用history.listen。好主意,除了在componentWillMount中调用时的某些原因外,history.listen不会被触发:

componentWillMount() {
let location;
this.props.history.listen(routerState => {
console.log('current location:' + routerState); //never logs anything...
location = routerState;
});
console.log(location); //'undefined'
let search = location;
console.log(search); //'undefined'
this.setState({ search: search.search }); //throws "Cannot read property search of undefined error
}

这似乎很奇怪,因为我在这里使用history.listen几乎与该链接中的上一张海报完全相同。我也尝试过将此逻辑放在组件DidMount中,结果相同。

我的组件在这里被路由器包装。

通过在侦听调用中实现逻辑以及将初始化逻辑放在组件DidMount中来解决此问题 - 这是必要的,因为history.listen仅在更改时触发,而不是在初始渲染时触发

我的代码:

componentWillMount() {
this.unlisten = this.props.history.listen(location => {
console.log('current location:' + location);
let query = qs.parse(location.search);
console.log(query) //logs an object with attributes based on the current query string
});
}
componentWillUnmount() {
this.unlisten();
}
componentDidMount() {
let query = qs.parse(this.props.location.search);
console.log(query); //logs an object with attributes based on the current query string
}

最新更新