[英]Render undefined in react component?
Why react crashes when it access props
of undefined
cannot read property of undefined
为什么当访问
undefined
props
cannot read property of undefined
时,react崩溃
ex One: Knowing that props.name is undefined this code will return an error. 前一个:知道props.name是未定义的,此代码将返回错误。
const component = (props) => {
return(
<p>{props.name}</p>
)
}
ex Two: Why in this case it is ok for react
to render without errors undefined
which in this case would return invisible. 例二:为什么在这种情况下可以
react
而没有undefined
错误,在这种情况下将返回不可见,这是可以的。
const componentTwo = () => {
return(
<p>{undefined}</p>
)
}
Writing props.name
should not give you the error cannot read property 'name' of undefined
. 编写
props.name
不应给您错误cannot read property 'name' of undefined
。 If the name
property doesn't exist on the props
object, props.name
will just be undefined
. 如果
props
对象上不存在name
属性,则props.name
将只是undefined
。
However, if there is eg no person
property on the props
object, props.person
will give you undefined
. 但是,如果例如
props
对象上没有person
属性,则props.person
将为您提供undefined
。 Trying to access name
on undefined
will then give rise to your error, because you can't access a property on undefined
. 尝试访问
undefined
name
将引起错误,因为您无法访问undefined
上的属性。
You could then use the &&
operator to make sure props.person
is set before using props.person.name
. 然后,您可以使用
&&
操作,以确保props.person
在使用前必须设定props.person.name
。
Example 例
const MyComponent = props => {
return <p>{props.person && props.person.name}</p>;
};
Also make sure that your component names start with an uppercase letter, or the component will be interpreted as a string instead of as a variable when using it . 另外,请确保您的组件名称以大写字母开头,否则使用该组件时 , 该组件将被解释为字符串而不是变量 。
If you are not passing props to the component, then props will be undefined
. 如果您没有将props传递给组件,则props将是
undefined
。 If this is true (that you are passing no props), then trying to access props.name
will throw that exact error! 如果这是真的(您没有传递任何道具),那么尝试访问
props.name
将抛出该确切错误! In order to ensure that props are given to the component, you can do as the other answer says, using the &&
operator. 为了确保将道具提供给组件,您可以使用
&&
运算符按其他答案所述进行操作。
const MyComponent = props => {
return <p>{props && props.name}</p>;
};
To answer the other part, React will render {undefined}
because there is nothing to render. 为了回答其他部分,React将渲染
{undefined}
因为没有要渲染的东西。 Just saying undefined
isn't trying to access a property of undefined. 只说
undefined
并不是试图访问undefined属性。 Similar to if you had an object like 类似于您有一个类似
var myObject = undefined
and then tried to access a name
property of this object: 然后尝试访问此对象的
name
属性:
console.log(myObject.name) //throws 'can not read property name of undefined'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.