代码之家  ›  专栏  ›  技术社区  ›  Toby Weed

响应路由器历史记录。侦听未在组件中运行将被装入

  •  1
  • Toby Weed  · 技术社区  · 6 年前

    我正在尝试创建一个SearchResults组件,它根据由SearchForm组件更新的查询字符串中的内容显示搜索结果。已经被推荐了 here 我用的是历史。听着。好主意,除了在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
    }
    

    这看起来很奇怪,因为我用的是历史。在这里听的和以前的海报一样。我还尝试将此逻辑放入componentdidmount中,结果相同。

    我的组件被这里的路由器包裹着。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Toby Weed    6 年前

    通过在listen调用内部实现逻辑,以及将初始化逻辑放在componentdidmount内部来解决这个问题——这是必要的,因为

    我的代码:

    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
    }