【问题标题】:Checking for Undefined In React在 React 中检查未定义
【发布时间】:2017-04-05 17:56:18
【问题描述】:

我有一个场景,我将数据从减速器传递到我的反应状态。

数据:

{
    "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"]
    })
}

我得到这个错误:

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

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

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

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

【问题讨论】:

  • 我认为您的错误是您的“正文”嵌套在“内容”中
  • @naomi 谢谢!我将代码固定为 blog.content 而不仅仅是内容,这是您的意思吗?我仍然遇到同样的错误。

标签: reactjs components redux undefined


【解决方案1】:

你可以做的是通过检查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"

【讨论】:

  • 啊,我明白了,我在引号中加上了 undefined。这成功了。谢谢!
  • 没问题。乐于助人
【解决方案2】:

我遇到了同样的问题.....我通过使用typeof()得到了解决方案

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

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

【讨论】:

  • 你为什么放弃投票你能有充分的理由发表评论吗?
  • 因为这里的 OR 是错误的!它应该是 AND。我们想要:不是未定义且不是空的。两者都应该是真的。
  • 感谢@Tom 发现了我的错误。
【解决方案3】:

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

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

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

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

【讨论】:

    【解决方案4】:

    您可以尝试添加一个问号,如下所示。这对我有用。

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

    【讨论】:

    【解决方案5】:

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

    ReactObject === '未定义'

    【讨论】:

    • undefined 的类型是 undefined 而不是 String
    猜你喜欢
    • 1970-01-01
    • 2018-10-17
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 2014-01-23
    相关资源
    最近更新 更多