最近写的项目遇到遇到关于react路由的问题,原项目中,查找的时候获取文本框上的值并跳转到查找结果页面,在componentDidMount函数中获取路由上的关键字,向其余组件传递参数keywords,向后台查询结果并返回。在从新查询的过程当中,发现虽然路由上的参数已经改变,然而页面上的查找结果并无更新。html
原代码:react
//定义变量 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来更新变量this
//组件更新时被调用 componentWillReceiveProps(nextProps){ let key = nextProps.match.params.key; this.setState({ key:key }) }
注意:像Article中也一样须要加入componentWillReceiveProps函数,加入后便可正常刷新页面。spa
ps:若有更好的解决方法,欢迎交流code