在 React 中检查未定义 [英] Checking for Undefined In React

查看:28
本文介绍了在 React 中检查未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a scenario where I'm passing data from a reducer into my react state.

数据:

{
    "id": 1,
    "title": "Test",
    "content": {
        "body": "sdfsdf"
        "image": "http://example.com"
    }
}

使用 componentWillRecieveProps,这非常适合检索标题.

Using componentWillRecieveProps, this works perfectly for retrieving the title.

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

但是,我很难检索嵌套字段.当我这样做时:

However, I'm having difficulty retrieving the nested fields. When I do this:

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

我收到此错误:

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

The error of an undefined body goes away after I click the debugger and the content is loaded. Is there anyway I can combat this issue?

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

I tried to check for undefined like this:

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

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

But this doesn't work either and I believe it's because the blog is undefined.

推荐答案

你可以做的是通过检查 nextProps.blog.content 是否未定义来检查你的 props 是否最初定义因为你的身体像

What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content is undefined or not since your body is nested inside it like

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

您不需要使用类型来检查未定义,只需使用严格运算符 !== 来比较值的类型和值

You need not use type to check for undefined, just the strict operator !== which compares the value by their type as well as value

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

In order to check for undefined, you can also use the typeof operator like

typeof nextProps.blog.content != "undefined"

这篇关于在 React 中检查未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆