我警告未处理的承诺被拒绝,并且undefined不是评估this.state.gridData [0] .brand的对象

这部分代码有问题



async componentDidMount() {
       const bikes = await fetchVehicleBasedOnType(VEHICLE_TYPES.TWO_WHEELER);
       this.setState({ bikes });
       const gridData = _.uniqBy(bikes, 'brand').map((K) => {
                return { brand: K.brand, logo: K.brand_logo };
                              });
       this.setState({ gridData,
                       selectedBikeBrand: this.state.gridData[0].brand,
                       selectedBikeBrandLogo: this.state.gridData[0].logo,
                       loading: false
                      });
        const listData = bikes
        .filter(item => item.brand === this.selectedBrand)
        .map(({ model, image }) => ({ model, modellogo: image }));
        this.setState({ listData });
  }





有人可以建议修改和修复以使此代码更好。

最佳答案

您没有将gridData分配给this.state,因此大概this.state.gridDataundefined。只需删除this.state的用法即可。
在尝试访问gridData上的属性之前,还应检查以确保gridData[0]不为空。

const gridData = _.uniqBy(bikes, 'brand').map((K) => {
    return { brand: K.brand, logo: K.brand_logo };
});

const firstItem = gridData[0] || { };

this.setState({
    gridData,
    selectedBikeBrand: firstItem.brand,
    selectedBikeBrandLogo: firstItem.logo,
    loading: false
});

关于javascript - React Native中未处理的 promise 拒绝,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47150644/

10-10 18:46