反应中嵌套对象的setState失败

时间:2018-01-28 16:01:55

标签: javascript reactjs

我有以下代码,nextProps.ad.submission.content是异步数据

componentWillReceiveProps(nextProps) {
    if(this.state.body !== get(nextProps.ad.submission.content, '')){
        this.setState({
            body: nextProps.ad && nextProps.ad.submission && nextProps.ad.submission.content
        })
    }
}                   

get来自lodash,为什么我收到Cannot read property 'content' of undefined的错误?这不是nextProps.ad && nextProps.ad.submission && nextProps.ad.submission.ad吗?

1 个答案:

答案 0 :(得分:0)

错误在此行

if(this.state.body !== get(nextProps.ad.submission.content, '')){

表示在nextProps.ad中您没有名为submission的属性,这意味着nextProps.ad.submission未定义,并且您尝试访问content的属性undefined

解决

检查nextProps.ad.submission是否未首先定义

componentWillReceiveProps(nextProps) 
{
    if(nextProps.ad.submission !== undefined)
    {
        if (this.state.body !== get(nextProps.ad.submission.content, '')) 
        {
            this.setState({
                body: nextProps.ad && nextProps.ad.submission && nextProps.ad.submission.content
            })
        }
    }
}