在 React 中检查未定义

新手上路,请多包涵

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

数据:

 {
    "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'){

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

原文由 lost9123193 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 585
2 个回答

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

原文由 Shubham Khatri 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

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

原文由 MD Ashik 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进