首页 > 解决方案 > React 中的 componentWillReceiveProps 问题

问题描述

如果我使用下面的代码,我会收到错误。

componentWillReceiveProps(nextProps) {
        if (nextProps.uploadImage.message === 'File uploaded') {
            this.setState({ photostatus: 'image' });
        }
        else {
            this.setState({ photostatus: 'input' });
        }
    }

但是如果我使用下面的代码,我不会收到错误

componentWillReceiveProps(nextProps) {
        if (nextProps.uploadImage) {
            this.setState({ photostatus: 'image' });
        }
        else {
            this.setState({ photostatus: 'input' });
        }
    }

我的错误如下

在此处输入图像描述

标签: reactjs

解决方案


你得到一个错误,因为你试图找到一个message属性的值undefined

你必须改变你的 if 条件是这样的,

componentWillReceiveProps(nextProps) {
    if (nextProps.uploadImage && (nextProps.uploadImage.message === 'File uploaded')) {
        this.setState({ photostatus: 'image' });
    }
    else {
        this.setState({ photostatus: 'input' });
    }
}

推荐阅读