为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

收到一只叮咚 2018-10-10 15:13:04
最近在做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`.我认为这个问题是比较常见的,不知道同道在处理这个问题上有没有什么比较好的实践?谢谢~
查看完整描述

1 回答

?
婷婷同学_

TA贡献1844条经验 获得超8个赞

我的项目引入了 redux , 所以没有遇到这种问题, 组件只负责发起异步请求, 请求后的数据都在 store 里, 组件根据 store 的变化去更新。 因为组件已经卸载, componentWillReceiveProps 并不会执行。 只是淡村的把异步请求的数据存在 store 里。


查看完整回答
反对 回复 2018-11-30
  • 1 回答
  • 0 关注
  • 716 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号