在 React 中检查未定义

Checking for Undefined In React

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

我收到此错误:

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

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

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

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

你可以做的是通过检查 nextProps.blog.content 是否未定义来检查你的道具是否最初定义,因为你的 body 像

一样嵌套在里面
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"

我遇到了同样的问题.....我通过使用 typeof()

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

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

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

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

并且,当 undefinedemptynull 值不是预期的;你可以让它更简洁:

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

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

ReactObject === 'undefined'

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

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