gpt4 book ai didi

javascript - 如果数组最初不存在,如何在 React 中使用 .join()

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

我有一个功能性的 React 组件,可以在 api 请求后显示信息。最初,它显示的对象是空白的,因为尚未发出请求。该对象中有一个数组,如下所示:

['US', 'USA', 'United States of America']

当我简单地显示数组时,在 api 请求之后,它会将其显示为页面上的单个字符串,ex 之间没有空格:

USUSAUnited States of America

当然,我想用 .join(', ' ) 对其进行格式化,以将字符串格式化为 US, USA, United States of America,但是在我添加 .join(', ') 后,它会抛出错误:

TypeError: props.modalCountry.alt_spellings is undefined

似乎 .join() 试图在存在实际的 modalCountry 对象之前在第一次渲染上运行。如何让此方法在对象和数组实际存在之前不运行?

最佳答案

在 react 中 - Booleans, Null, and Undefined Are Ignored ,因此如果数组不存在,您可以返回 nullundefined。另一种选择是提供默认数组。

选项 1 - 使用 short circuit evaluation如果数组尚不存在,则跳过 array.join():

const Component = ({ arr = [] }) => (
<div>
{arr && arr.join()}
</div>
);

选项 2 - 如果没有数组,则渲染 null:

const Component = ({ arr = [] }) => (
<div>
{arr ? arr.join() : null}
</div>
);

选项 3 - 提供默认数组作为值:

const Component = ({ arr = [] }) => (
<div>
{arr.join()}
</div>
);

关于javascript - 如果数组最初不存在,如何在 React 中使用 .join(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53342040/

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