作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个功能性的 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 ,因此如果数组不存在,您可以返回 null
或 undefined
。另一种选择是提供默认数组。
选项 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/
我是一名优秀的程序员,十分优秀!