2016-11-22 48 views
8

我有一个场景,我将数据从reducer传递到我的反应状态。检查未定义在反应中

数据:

{ 
    "id": 1, 
    "title": "Test", 
    "content": { 
     "body": "sdfsdf" 
     "image": "http://example.com" 
    } 
} 

使用componentWillRecieveProps,这完全适用于检索标题。

componentWillReceiveProps(nextProps) { 
    this.setState({ 
     title: nextProps.blog.title, 
    }) 
} 

但是,我很难检索嵌套字段。当我这样做:

componentWillReceiveProps(nextProps) { 
    console.log("new title is", nextProps.blog.title); 
    console.log("new body content is", nextProps.blog.content["body"]); 
    this.setState({ 
     title: nextProps.blog.title, 
     body: nextProps.blog.content["body"] 
    }) 
} 

我得到这个错误:

enter image description here

未定义体的错误消失我点击调试器和内容加载后。无论如何,我可以解决这个问题吗?

我试图检查未定义这样的:

if (typeof nextProps.blog.content["body"] != 'undefined'){ 

但是,这也不行,我相信这是因为博客是不确定的。

+1

我觉得你的错误就在于,你的“身体”嵌套在“内容” – naomi

+0

@naomi谢谢!我将我的代码固定到blog.content而不是仅仅是内容,那是什么意思?我仍然遇到同样的错误。 – lost9123193

回答

5

你可以做的是检查是否你的道具通过检查最初还是没有定义,如果nextProps.blog.content未定义或不是因为你的身体是嵌套在它像

componentWillReceiveProps(nextProps) { 

    if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) { 
     console.log("new title is", nextProps.blog.title); 
     console.log("new body content is", nextProps.blog.content["body"]); 
     this.setState({ 
      title: nextProps.blog.title, 
      body: nextProps.blog.content["body"] 
     }) 
    } 
} 

你不需要使用类型检查未定义,只是严格的运营商!==,它的值由它们的类型,以及作为比较值

为了检查不确定的,你也可以使用typeof运营商像

typeof nextProps.blog.content != "undefined" 
+1

啊,我看到了,我在报价中放入了未定义的字符。这个伎俩。谢谢! – lost9123193

+1

没问题。乐于帮助 –

0

我面对同样的问题.....我用typeof()

if (typeof(value) !== 'undefined' || value != null) { 
     console.log('Not Undefind or Not Null') 
    } else { 
     console.log('Undefind or Null') 
} 

得到解决您必须使用typeof()来确定undefined