react相关小技巧
一、我们在项目中切换路由的时候可能会遇到
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the xxx component.
关于react中切换路由时报以上错误,实际的原因是因为在组件挂载(mounted)之后进行了异步操作,比如ajax请求或者设置了定时器等,而你在callback中进行了setState操作。当你切换路由时,组件已经被卸载(unmounted)了,此时异步操作中callback还在执行,因此setState没有得到值。
最简单也是最有效的方法
componentWillUnmount = () => { this.setState = (state,callback)=>{ return; }; }