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

时间:2018-10-10 14:38:26

标签: javascript reactjs react-native react-native-navigation

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

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

我尝试删除componentWillUnmount中的事件侦听器,但未成功,显然我在做错事。

此外,我已经尝试使用此方法this.props.navigation.isFocused()并再次正常运行,但是如果我在第三个屏幕上并旋转设备并返回,Dimensions事件侦听器看不到更改和样式是一团糟。

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

谢谢。

//tagA[@attrA[matches('VAL\d')]]

componentWillUnmount

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

2 个答案:

答案 0 :(得分:3)

您应该像这样制作一个命名函数(准确地说是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);
  }

PS:别忘了绑定功能

答案 1 :(得分:2)

分别定义一个函数,以将侦听器添加/删除到该特定函数。 一旦安装了组件,还应该添加侦听器,以避免在未安装的组件上设置状态

componentDidMount () {
    Dimensions.addEventListener('change', updateDimensions)
}
componentWillUnmount() {
    Dimensions.removeEventListener('change', updateDimensions)
}
updateDimensions() {
  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;
}