react-router那些事儿

切换路由时,控制台警告

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 State component.

前端发了一个异步请求,在异步请求的回调中使用this.setState方法;当异步请求发送后接口数据还没返回期间,做了路由切换的操作,于是上一个react组件就被销毁了。但是这时,刚才向后台发送的异步请求却在这时返回了,于是执行this.setState方法,但是,这个组件的生命周期已经结束,被销毁了,于是就出现这样的警告。总之,是因为组件被销毁了,又执行了this.setState方法。

解决方案:

自己维护一个_isMounted,在componentDidMount回调中设置为true,在componentWillUnmount设置为false,就可以判断销毁状态了。

if (this._isMounted) {
    this.setState({});
}

官网说,这个警告为了帮助开发者捕捉bug,当你销毁组件后,又调用了this.setState方法,表明你的组件很有可能未正常清理,可能造成内存泄漏。

路由刷新,404,借助服务器配置。express,nginx。

原文地址:https://www.cnblogs.com/camille666/p/react_router.html