React-router history.listen没有在componentWillMount中运行

时间:2018-06-20 21:11:15

标签: reactjs react-router

我试图制作一个SearchResults组件,该组件根据查询字符串中的内容显示搜索结果,该字符串由SearchForm组件更新。建议here使用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.list几乎完全像以前的海报在该链接中那样。我也尝试过将此逻辑放入componentDidMount中,结果相同。

我的组件在这里被withRouter包装。

1 个答案:

答案 0 :(得分:1)

通过在listen调用中实现逻辑,以及将初始化逻辑置于componentDidMount中来解决此问题-这是必需的,因为 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
}