在React中检查未定义的内容

66
最初的回答:我有一个场景,在这个场景中我正在将数据从一个reducer传递到我的React状态中。
数据:
{
    "id": 1,
    "title": "Test",
    "content": {
        "body": "sdfsdf"
        "image": "http://example.com"
    }
}

使用componentWillReceiveProps,这对于检索标题的操作非常完美。最初的回答。
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

在我点击调试器并加载内容后,未定义的正文错误消失了。有没有办法解决这个问题?

我尝试像这样检查未定义:

Original Answer:

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

但这也行不通,我认为是因为博客未定义。最初的回答。

1
我认为你的错误在于你的“body”嵌套在“content”内部。 - naomi
1
@naomi 谢谢!我已经修复了我的代码,使用了 blog.content 而不是仅仅的 content,这是你的意思吗?但我仍旧遇到了同样的错误。 - lost9123193
5个回答

59

你可以通过检查 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 来检查未定义的变量,只需使用严格比较运算符 !== 即可,它不仅比较值,也比较类型。

为了检查变量是否未定义,您也可以使用 typeof 运算符,例如:

typeof nextProps.blog.content != "undefined"

2
啊,我明白了,我把未定义的内容放在引号里了。这样就可以了。谢谢! - lost9123193
3
没问题。很乐意帮忙。 - Shubham Khatri

21

我曾面临相同的问题......但是我通过使用typeof()得到了解决方案。

if (typeof(value) !== 'undefined' && value != null) {
         console.log('Not Undefined and Not Null')
  } else {
         console.log('Undefined or Null')
}

你必须使用 typeof() 来识别 undefined


3
为什么你要踩我的帖子?能否给出充分的理由并附上评论?请确保评论表达完整且易于理解,但不要改变原意。 - MD Ashik
1
因为这里使用了OR,是错误的!应该使用AND。我们想要:既不是undefined也不是null。两者都应该为true。 - Tom
1
感谢 @Tom 指出我的错误。 - MD Ashik

5

如果你还需要检查nextProps.blog是否为undefined,你可以在一个if语句中完成,像这样:

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

当不期望出现 undefinedemptynull 值时,您可以使其更加简洁:

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

5

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

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

注意:在使用之前,请检查您的环境是否支持可选链 - thisgeek

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

ReactObject === 'undefined'


1
undefined 的类型是 undefined 而不是 String - Laxmikant Dange

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接