React native:未定义不是对象

时间:2019-09-24 04:21:32

标签: reactjs react-native

我正在使用expo制作React Native应用,并且在解析api的响应数据时遇到了一些麻烦。以下是来自api的示例响应,我的目标是从天气数组中检索main。我可以很好地记录天气数组,但是当我放置state.weather[0].main时,它将引发未定义的对象错误。

Object {
  "clouds": Object {
    "all": 20,
  },
  ...,
  "weather": Array [
    Object {
      "description": "few clouds",
      "icon": "02d",
      "id": 801,
      "main": "Clouds",
    },
  ],
}

下面是我的代码,我从useEffect()钩子上的api中获取。最初,日志显示未定义,但正确提取后,日志state.weather[0].main除外。我刚刚开始对来自Android的本地应用程序做出反应,希望你们能为我提供帮助,但现在我呆了一天。谢谢

const HomeScreen = ({ navigation }) => {
  const { state: { defaultCity } } = useContext(CitiesContext);
  const { state: { weather }, fetchWeather } = useContext(WeatherContext);    

  useEffect(() => {
    if (defaultCity) {
      fetchWeather(defaultCity);
    }
  }, []);

  console.log(weather);
  console.log(typeof (weather[0]));
  console.log(weather[0]);
  console.log(weather[0].main);

  return (
    <View style={styles.container}>
      <LinearGradient
        // {...weatherBgProvider[weather.weather.main]}
        colors={['#000', '#fff']}
        style={styles.gradient}
      >
        <SafeAreaView
          style={{
            position: 'relative'
          }}
          forceInset={{ top: 'always' }}
        >
          <View style={{ marginTop: Header.HEIGHT, flex: 1 }}>
            <Text >{JSON.stringify(state)}</Text>
          </View>
        </SafeAreaView>
      </LinearGradient>
    </View>
  );
};

1 个答案:

答案 0 :(得分:1)

如果您尝试在渲染器中记录数据,则可以这样做:

<View>{This.state.weather[0] && console.log(this.state.weather[0]) }</View>

因此您在记录数据之前先检查它是否存在 希望你有主意并为你工作

更新

如果您的主系统不起作用,请首先尝试将您的对象解析为数组,如下所示:

第一种方法 使用lodash(npm i --dev lodash)并将其导入您的项目中

Import _ from "lodash";

const newdata = _.compact(Object.values(yourobject))

然后您可以使用newdata,我认为您的问题将得到解决

第二种方式 使用_.mapKeys(yourdata,"id")并将新数据放入变量中,例如const newdata

我希望它能起作用