3

I'm using react, alt.js, and react-router, and building an application with basic CRUD. There is a menu item for "Create Item", and it brings up a modal (using react-bootstrap...) and on submit it fires an action to create some model on the backend, and then does a browserHistory.push (as recommended in react-router docs) when that completes go to the item page for the newly created item.

So in the basic case, this works. For example if I'm on the main app page it works. However, if I was already on the item detail page for a different item (let's say I was on /item/1 and I just created /item/2, so I'm trying to redirect to /item/2 from page /item/1).

And my async load logic (well, the action call at least, for fetchItem) is in componentDidMount of the ItemViewPage react component, which seems pretty typical based on all the examples I can find online.

And the problem is, if the page was currently already rendered, componentDidMount never gets called, because the component is already mounted(!). And so my page URL updates to /item/2, but the contents are still for /item/1.

So, my question is....Yeah. Am I wrong to initiate data load from componentDidMount? Am I supposed to do it some other lifecycle method (say, componentWillReceiveProps, since the react router will set a new id)? Or is there some other place entirely where I should be firing off data load from (e.g. does react-router have some feature I'm not aware of that handles this)?

4

1 回答 1

2

由于 React 很聪明,并且知道您在路由中重复使用该组件,因此该组件将保持挂载状态。您选择的生命周期方法将无法处理该作业,因为它在组件的初始安装时被调用一次。

我建议您使用componentWillReceiveProps并在那里您可以检查,比如说,id您的项目的字段是否已更改。这意味着您可能应该更新,因为要呈现新的、不同的数据。

于 2016-07-01T03:56:21.780 回答