最近寫的項目遇到遇到關於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:如有更好的解決方法,歡迎交流