【发布时间】:2018-10-10 14:38:26
【问题描述】:
我设置了一些动态样式,除了卸载组件外,一切正常。然后它会抛出一个错误:Can't call setState (or forceUpdate) on an unmounted component。
这是堆栈导航器中的第二个屏幕,当我转到第三个时,一切都很好,但是当我转到第一个并且组件被卸载时,它会引发错误。
我试图删除 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;
});
}
componentWillUnmount
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;
});
}
【问题讨论】:
标签: javascript reactjs react-native react-native-navigation