我正在使用React + Redux並希望知道如何正確更新狀態。使用React Redux更新路由更改狀態
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/questions" component={App}>
<Route path="subject">
<Route path="english" component={displayQuestions} />
<Route path="math" component={displayQuestions} />
<Route path="science" component={displayQuestions} />
<Route path="history" component={displayQuestions} />
</Route>
</Route>
...
</Router>
</Provider>
, document.querySelector('.app'));
這些途徑可以單擊的選項卡(如圖所示一個例子):
<div>
<Link to={'/questions/english'}>English</Link>
</div>
...
在我的渲染方法displayQuestions,我做了檢查
if (!questions) {
Loading content
}
return (
{this.renderQuestions()}
)
所以,當用戶導航到頁面,在我的componentDidMount()中,我使用了一個動作方法this.props.fetchQuestions,然後它向我的後端發出異步請求,遍歷reducer,然後進入渲染方法abov即在renderQuestions函數中,在renderQuestions中,我只是從this.props.questions中獲取問題。
但是,我配置路由的方式,componentDidMount只發生一次。例如,如果我在英文選項卡上選擇,我會得到componentDidMount,但是如果我點擊數學或科學,url會更改,但componentDidMount不會再被調用。
如果我點擊一個按鈕,它使用了一個不同的組件,比如userProfile,那麼所有的事情都會按照預期的方式發生。但我認爲,因爲我在每個問題/主題路徑中使用相同的組件,所以componentDidMount不會再被調用。
那麼如何更新url更改的狀態?什麼是React + Redux方式?沒有反模式,請。
編輯:
現在,我來這個答案:
componentDidUpdate(nextProps) {
if (this.props.route.path !== nextProps.route.path) {
let subject = this.props.location.pathname.split('/')[3];
this.props.fetchQuestions(subject);
}
return false;
}
這將阻止可能發生的無限循環。但是一定有更好的辦法。
我不知道這件事,但我認爲你應該做它componentWillReceiveProps –