javascript - 如何避免在 React 上遍历?
问题描述
我看到一个反复出现的“错误”,如果它是一个错误或只是一些 React 常规行为,我实际上并没有。
我从 API 获取一些数据,然后在一些输入上设置这些值。
所以,看这个例子:
<select
value={
(startupFourthStepForm &&
startupFourthStepForm.my_team &&
startupFourthStepForm.my_team[index] &&
startupFourthStepForm.my_team[index].country_code_mobile)}
required
id="select-country"
onChange={e =>
handleAddingNewObjectToFormArray(
e.currentTarget.value,
'country_code_mobile',
index,
)
}
>
<option value="" className="empty-option">
Select Country Code
</option>
{COUNTRY_CODE_LIST.map(item => (
<option value={item.code} id={item.name} key={item.name}>
{item.name} {item.code}
</option>
))}
</select>
问题是关于这段代码:
value={
(startupFourthStepForm &&
startupFourthStepForm.my_team &&
startupFourthStepForm.my_team[index] &&
startupFourthStepForm.my_team[index].country_code_mobile)}
每次我想通过 API 渲染某些东西时,我都需要进行这种遍历。否则我得到一个错误。
就像如果我这样做,
value={startupFourthStepForm.my_team[index].country_code_mobile}
我会收到类似的错误can not read property 0 of undefined
或类似的东西。
我正在使用 lodash 顺便说一句。
那么,我该怎么做才能避免这种情况呢?
解决方案
据我了解,您的问题不是具体反应,而是您只想在没有所有丑陋条件的情况下访问深层属性。
为此,既然您已经使用了lodash
,那么您也可以使用loadsh#get
.
它可以像:
const countryCodeMobile = _.get(startupFourthStepForm, `my_team[${index}].country_code_mobile`);
//...
value={countryCodeMobile}
推荐阅读
- javascript - 在 chrome 的性能选项卡中调查“其他”时间
- c# - ExecuteScalar, ExcuteReader...已经有一个打开的 DataReader 与此命令关联,必须先关闭
- apache-nifi - 将目录作为参数传递给 ExecuteStreamCommand
- javascript - 将组件作为字符串存储在变量中并在Vue JS中通过变量呈现
- java - 电子产品商店
- python - json字典python请求中的转义字符串
- android - Gson 对象解析
- c# - Bot Channels Registration SocketException - 现有连接被远程主机强行关闭
- android - 我可以实时从 Firebase 数据库中读取数据并在 Android 应用中不断更新吗?
- javascript - 状态已更改,但组件未刷新