如何避免在React上遍历?

时间:2019-05-24 17:40:38

标签: javascript reactjs ecmascript-6

我看到一个经常发生的“错误”,如果是错误或只是一些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 btw。

那么,我该怎么避免这种情况?

2 个答案:

答案 0 :(得分:2)

据我了解,您的问题并非针对特定问题,而是您只想访问深层属性,而没有所有丑陋的条件。

为此,由于您已经使用lodash,因此也可以使用loadsh#get

它可以像这样:

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

//...

value={countryCodeMobile}

答案 1 :(得分:0)

有一个关于在javascript中进行可选链接的建议,可以通过babel来获得:

https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining

基本上,您是这样编写代码的:

startupFourthStepForm?.my_team?.[index]?.country_code_mobile