React Native 无法读取未定义的 属性 '0'

React native cannot read property '0' of undefine

我是 ReactJS 的新手,今天我遇到了一些问题。 我目前正在使用 Redux 来存储我的数据,并且我能够从道具中检索所有数据。

即。

const { recipe, loadingRDetail } = this.props;
console.log(recipe.macros); 

配方宏会显示数组中的 5 个值。 Array Image Console Log

但是当我试图访问数组时,它会抛出一个错误“无法读取未定义的属性'0'”。

我试过了

console.log(recipe.macros[0])

const {macros} = recipe;
macros.map((i) => {
    ....
}...

这两个我都不走运

这是我得到的错误 Red Warning error

其实是因为你的宏数据是异步加载的,所以你要加一个测试,看看是否加载好了。

你可以试试这个:

const {macros} = recipe;
if (macros && macros.length) {
  macros.map((i) => {
      ....
   }...
}

或者如果您已经在渲染方法中,您可以试试这个:

const {macros} = recipe;
return (
  {
    macros && macros.length && /* It will check if macros has elements inside */
      macros.map((i) => {
          ....
       }...
    }
  }
)