在React

时间:2016-11-22 06:44:54

标签: reactjs components redux undefined

我有一个场景,我将数据从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'){

但这也不起作用,我相信这是因为博客未定义。

5 个答案:

答案 0 :(得分:20)

你可以做的是检查你的道具是否是最初定义的,检查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"]
       })
    }
}

你不需要使用type来检查undefined,只需要使用严格的运算符!==来比较值的类型和值

为了检查未定义,您还可以使用typeof运算符,如

typeof nextProps.blog.content != "undefined"

答案 1 :(得分:2)

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

得到了解决方案
if (typeof(value) !== 'undefined' || value != null) {
         console.log('Not Undefined or Not Null')
  } else {
         console.log('Undefined or Null')
}

您必须使用typeof()标识undefined

答案 2 :(得分:2)

您可以尝试如下添加问号。这对我有用。

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

答案 3 :(得分:0)

如果您还需要检查nextProps.blog是否不是undefined;您可以在单个if语句中完成此操作,如下所示:

if (typeof nextProps.blog !== undefined && typeof nextProps.blog.content !== undefined) { // }

并且,当不需要undefinedemptynull值时;您可以使其更简洁:

if (nextProps.blog && nextProps.blog.content) { // }

答案 4 :(得分:-3)

您可以使用以下代码检查未定义的对象。

ReactObject ==='未定义'