React 路由参数改变页面不刷新问题

最近写的项目遇到遇到关于react路由的问题,原项目中,查找的时候获取文本框上的值并跳转到查找结果页面,在componentDidMount函数中获取路由上的关键字,向其他组件传递参数keywords,向后台查询结果并返回。在重新查询的过程中,发现虽然路由上的参数已经改变,然而页面上的查找结果并没有更新。

原代码:

//定义变量
state={
     key:""
}

//获取值
componentDidMount(){
        let key = this.props.match.params.key;
        this.setState({
            key:key
      })
}

//传递参数
 <Article keywords={`${this.state.key}`}/>

随后排查后发现页面获取key时是在componentDidMount中获取的,而componentDidMount只在第一次渲染后调用,因此虽然路由改变了但是并没有再次调用函数,具体Recat的生命周期可参考http://www.runoob.com/react/react-component-life-cycle.html

因此在参数改变的时候,可以利用componentWillReceiveProps来更新变量

//组件更新时被调用 
componentWillReceiveProps(nextProps){
        let key = nextProps.match.params.key;
        this.setState({
            key:key
        })
}

注意:像Article中也同样需要加入componentWillReceiveProps函数,加入后即可正常刷新页面。

ps:如有更好的解决方法,欢迎交流

原文地址:https://www.cnblogs.com/GEWUYE/p/8877187.html