如何使用TypeError解决此问题

时间:2019-08-01 12:06:14

标签: javascript typescript react-native

我有打字稿代码。单击某些按钮时,必须有一些功能。以componentwillmount为界。

componentWillMount() {
    const { species } = this.props;
    const selectedSpecies =
    species.find(v => v.id == SPECIES_TYPE_CATTLE) || null;
    if (selectedSpecies) {
      this.onSpeciesSelect(selectedSpecies);
     }
}
  

TypeError:未定义不是对象(正在评估'species.find')

2 个答案:

答案 0 :(得分:4)

在进行species之前,您应该检查.find

const selectedSpecies = species ? species.find(v => v.id == SPECIES_TYPE_CATTLE) : null;

答案 1 :(得分:0)

selectedSpecies可能是异步操作的结果,并且在componentDidMount执行其工作时其值不可用。因此,它应该具有默认值或在具有默认值之前进行检查