我收到这个警告:
警告:只能更新已安装或安装的组件。这通常意味着您在已卸载的组件上调用了setState,replaceState或forceUpdate。这是一个无操作。
请检查QuantityCounter组件的代码。
当我将QuantityCounter组件放在ProductCardScreen组件中时(当我将它作为此特定父组件的子组件时),就会发生这种情况。在上一页中,它也在不同的父组件中使用,但这不会发生。
如果我注释掉componentDidMount()函数中的代码(在QuantityCounter中),那么我不会收到警告消息,但我的QuantityCounter组件不再有效。
constructor(props) {
super(props);
this.state = {total: 0};
}
componentDidMount() {
AsyncStorage.getItem(this.props.data.productId.toString()).then((resultCount) => {
if (resultCount !== null) {
this.setState({
total: parseInt(resultCount)
});
} else {
this.setState({
total: 0
});
}
});
}
我见过其他人在网上询问这个警告,但到目前为止我看到的答案都没有帮助。我假设子组件在父组件之前安装,但我不确定。有谁知道如何摆脱这样的警告信息?如何检查组件是否已卸载?
理想情况下,在卸载之前,应在componentWillUnmount中取消任何回调。
要么
只需在componentDidMount中将_isMounted属性设置为true,并在componentWillUnmount中将其设置为false,并使用此变量检查组件的状态。
我认为你的组件正在等待一些数据并在数据到达之前卸载。我遇到了同样的问题并在我通过反应文档官方页面isMounted is an Antipattern时解决了。
感谢Gabriel Blue,我能够理解我需要在AsyncStorage中进行检查,而不是像以前那样把它包起来。这对我有用:
componentDidMount() {
AsyncStorage.getItem(this.props.data.productId.toString()).then((resultCount) => {
if (resultCount !== null && this.refs.quantityCounter) {
this.setState({
total: parseInt(resultCount)
});
} else if (this.refs.quantityCounter) {
this.setState({
total: 0
});
}
});
}
对于HTML我将ref标签添加到最外层视图:
<View ref="quantityCounter" style={styles.counterContainer}>