如何删除事件侦听器,以便在卸载组件时不会尝试更新状态?

Fat*_*zla 4 javascript reactjs react-native react-native-navigation

我设置了一些动态样式,除卸载组件外,一切正常。然后它抛出一个错误:无法在未安装的组件上调用 setState(或 forceUpdate)。

它是堆栈导航器中的第二个屏幕,当我转到第三个屏幕时,一切都很好,但是当我转到第一个并卸载组件时,它会引发错误。

我试图删除 componentWillUnmount 中的事件侦听器但没有成功,显然我做错了什么。

另外,我已经尝试过这种方法 this.props.navigation.isFocused() 并且它再次工作得很好,但是如果我在第三个屏幕上并旋转设备并返回,Dimensions 事件侦听器看不到更改和样式是一个烂摊子。

那么如何在卸载组件时停止事件侦听器?

提前致谢。

constructor(props) {
    super(props);
    Dimensions.addEventListener("change", dims => {
      // this.props.navigation.isFocused() ?
      this.setState({
        resStyles: {
          imageFlex: Dimensions.get("window").height > 500 ? "column" : "row",
          imageHeight: Dimensions.get("window").height > 500 ? "50%" : "100%",
          infoHeight: Dimensions.get("window").height > 500 ? "50%" : "100%",
          infoWidth: Dimensions.get("window").height > 500 ? "100%" : "50%"
        }
      });
      // : null;
    });
  }
Run Code Online (Sandbox Code Playgroud)

组件将卸载

componentWillUnmount() {
    console.log("Unmounted");

    Dimensions.removeEventListener("change", dims => {
      // this.props.navigation.isFocused() ?
      this.setState({
        resStyles: {
          imageFlex: Dimensions.get("window").height > 500 ? "column" : "row",
          imageHeight: Dimensions.get("window").height > 500 ? "50%" : "100%",
          infoHeight: Dimensions.get("window").height > 500 ? "50%" : "100%",
          infoWidth: Dimensions.get("window").height > 500 ? "100%" : "50%"
        }
      });
      // : null;
    });
  }
Run Code Online (Sandbox Code Playgroud)

evg*_*tia 7

你应该像这样创建一个命名函数(确切地说是Methode)

fun_name(){
      // this.props.navigation.isFocused() ?
  this.setState({
    resStyles: {
      imageFlex: Dimensions.get("window").height > 500 ? "column" : "row",
      imageHeight: Dimensions.get("window").height > 500 ? "50%" : "100%",
      infoHeight: Dimensions.get("window").height > 500 ? "50%" : "100%",
      infoWidth: Dimensions.get("window").height > 500 ? "100%" : "50%"
    }
  });
  // : null;
}

constructor(props) {
    super(props);
    Dimensions.addEventListener("change", this.fun_name);
  }

componentWillUnmount() {
    console.log("Unmounted");

    Dimensions.removeEventListener("change", this.fun_name);
  }
Run Code Online (Sandbox Code Playgroud)

PS:别忘了绑定函数