最近在做react的一个个人项目遇到如下一个问题:
我用到了react-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`.
我认为这个问题是比较常见的,不知道同道在处理这个问题上有没有什么比较好的实践?
谢谢~
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我的项目引入了 redux , 所以没有遇到这种问题, 组件只负责发起异步请求, 请求后的数据都在 store 里, 组件根据 store 的变化去更新。 因为组件已经卸载, componentWillReceiveProps 并不会执行。 只是淡村的把异步请求的数据存在 store 里。