gpt4 book ai didi

javascript - react : Is there a way to avoid type errors if a part of a prop isn't available?

转载 作者:行者123 更新时间:2023-11-28 12:58:58 26 4
gpt4 key购买 nike

我将数据数组作为 Prop 传递,并映射内容。

父组件

getDefaultProps: function() {
return {
dataArrays: [0,0,0],
}

<ChildComponent
dataArrays = {this.props.dataArrays}
name = {this.props.name}
/>
<小时/>

子组件

this.props.dataArrays.map((block, index) => (
<div className={index}>
{block.fullName}
</div>

我通常从 api 传递 props,所以这很好,但是如果数据由于某种原因没有返回,我试图让它仍然使用默认 props 正确渲染。如果我不传入 props,则 {block.fullName} 会失败,因为 fullName 嵌套在该 prop 中,而不是直接作为 prop。有没有办法做类似的事情:`{block.fullName || “不可用”}

最佳答案

The logical && operation是在尝试评估对象的属性之前检查对象是否存在的常见方法:

// In this case, will evaluate to undefined if block is falsey
this.props.dataArrays.map((block, index) => (
<div className={index}>
{block && block.fullName}
</div>
));

另一种方法是定义 default parameter在你的函数中,以保证它有一定的值(value):

// In this case, block will be a default object if the parameter is falsey
this.props.dataArrays.map((block = {fullName: "Not Available"}, index) => (
<div className={index}>
{block.fullName}
</div>
));

另一种方法是执行 ternary conditional :

// In this case, if block is falsey it will evaluate to "Not Available"
this.props.dataArrays.map((block, index) => (
<div className={index}>
{block ? block.fullName : "Not Available"}
</div>
));

关于javascript - react : Is there a way to avoid type errors if a part of a prop isn't available?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52433600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com