首页 > 解决方案 > 如何避免在 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 顺便说一句。

那么,我该怎么做才能避免这种情况呢?

标签: javascriptreactjsecmascript-6

解决方案


据我了解,您的问题不是具体反应,而是您只想在没有所有丑陋条件的情况下访问深层属性。

为此,既然您已经使用了lodash,那么您也可以使用loadsh#get.

它可以像:

const countryCodeMobile = _.get(startupFourthStepForm, `my_team[${index}].country_code_mobile`);

//...

value={countryCodeMobile}

推荐阅读