为什么我收到此警告:只能更新已安装或安装的组件?

时间:2018-02-28 12:59:32

标签: javascript reactjs react-native

我收到了这个警告:

  

警告:只能更新已安装或安装的组件。这通常   表示你在一个上调用了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
                });
            }
        });
    }

我见过其他人在网上询问这个警告,但到目前为止我看到的答案都没有帮助。我假设子组件在父组件之前安装,但我不确定。有谁知道如何摆脱这样的警告信息?如何检查组件是否已卸载?

3 个答案:

答案 0 :(得分:0)

  

理想情况下,在卸载之前,应在componentWillUnmount中取消任何回调。

  

只需在componentDidMount中将_isMounted属性设置为true,并在componentWillUnmount中将其设置为false,并使用此变量检查组件的状态。

source

答案 1 :(得分:0)

我认为你的组件正在等待一些数据并在数据到达之前卸载。我遇到了同样的问题并在我通过反应文档官方页面isMounted is an Antipattern时解决了这个问题。

答案 2 :(得分:0)

感谢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}>
相关问题