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();
  }

 

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章