我设置了一些动态样式,除了卸载组件外,一切都工作正常。然后它会抛出一个错误:无法在未安装的组件上调用 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;
});
}
组件将卸载
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;
});
}
最佳答案
你应该像这样创建一个命名函数(准确地说是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:不要忘记绑定(bind)函数
关于javascript - 如何删除事件监听器,以便在卸载组件时它不会尝试更新状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52742755/