react redux 订阅模式报错解决方法

1,错误原因

//订阅模式
    this.cancelSub = store.subscribe(() => {
      this.setState(store.getState());
    });

众所周知redux 订阅模式可以在store发生改变的时候,回调方法但是页面且回去的时候会报错

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

2,解决方法

需要在页面卸载的时候调用取消订阅方法

取消订阅的方法就是订阅方法的返回值

cancelSub = () => {};
  
  componentDidMount() {
    //订阅模式
    this.cancelSub = store.subscribe(() => {
      this.setState(store.getState());
    });
  }
  componentWillUnmount() {
    this.cancelSub();
  }

 

 

版权声明:本文为qq_32674347原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。