关于react的组件和路由的一个问题

最近在做react的一个个人项目遇到如下一个问题:

我用到了react-router,比如像下面这样(实际比这个复杂,我做了一些简化)

 <Router history={hashHistory}>

        <Route path="/" component={IndexContainer}>

            <IndexRoute component={HomePage} />

            <Route path="select" component={Select} />

        </Route>

 </Router>

其中HomePage组件中在constructor中会调用一些fetch等异步函数,而假设用户快速切换到select,这个时候根据react-router的文档,HomePage组件是会被卸载的,而这个时候之前fetch等异步函数的回调函数还没来的及执行,因此等这些回调函数执行的时候,其实HomePage组件已经被卸载掉了,所以会报如下错误:

warning.js:36 Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

我认为这个问题是比较常见的,不知道同道在处理这个问题上有没有什么比较好的实践?

谢谢~


收到一只叮咚
浏览 717回答 1
1回答

婷婷同学_

我的项目引入了 redux , 所以没有遇到这种问题, 组件只负责发起异步请求, 请求后的数据都在 store 里, 组件根据 store 的变化去更新。 因为组件已经卸载, componentWillReceiveProps 并不会执行。 只是淡村的把异步请求的数据存在 store 里。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript