【发布时间】:2016-11-26 23:55:26
【问题描述】:
我正在使用 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,然后它向我的后端发出异步请求,通过减速器,然后进入渲染上面的方法。在 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 上做
标签: reactjs redux react-router react-redux react-router-redux