繁体   English   中英

未定义不是 object(评估“users.map”)反应原生

[英]Undefined is not an object (evaluating 'users.map') REACT NATIVE

您好,由于某种原因,当我尝试通过 state 从另一个组件传递到 map 时,我收到此错误 undefined is not an object ('evaluating usermap') 并且我不知道为什么。

 import React, {useState, useEffect} from 'react'; import {StyleSheet, Text, View, Image, ScrollView} from 'react-native'; import Card from '../../molecules/Card'; import Axios from 'axios'; const HomeScreen = () => { const [users, setUsers] = useState([]); useEffect(() => { //Fetch // fetch('https://reqres.in/api/users') //.then(res => res.json()) //.then(json => setUsers(json.data)); //Axios Axios.get('https://jsonplaceholder.typicode.com/users').then(res => setUsers(res.data.data), ); }, []); return ( <View style={styles.container}> <Text style={styles.title}>Users List</Text> <ScrollView showsVerticalScrollIndicator={false}> {users.map(item => ( <Card key={item.id} fullName={`${item.first_name} ${item.last_name}`} userName={item.userName} email={item.email} phone={item.phone} /> ))} </ScrollView> </View> ); }; export default HomeScreen; const styles = StyleSheet.create({ container: { flex: 1, paddingHorizontal: 15, paddingTop: 20, }, title: { fontSize: 36, fontWeight: '700', }, card: { marginTop: 15, alignItems: 'center', }, name: { fontSize: 18, fontWeight: '700', }, email: { fontSize: 16, color: 'grey', marginTop: 10, }, image: { height: 150, width: 150, marginTop: 10, }, });

我不明白当我将 map 用于我的代码时会发生什么。 它说“未定义不是 object(评估'users.map')”有人可以帮助我。 先感谢您。

  useEffect(() => {
    //Fetch
    // fetch('https://reqres.in/api/users')
    //   .then(res => res.json())
    //   .then(json => setUsers(json.data));
    //Axios
    Axios.get("https://jsonplaceholder.typicode.com/users").then((res) =>
      console.log(res.data)
    );
  }, []);

在测试您的代码 res.data.data 不存在后,您应该将 state 设置为 res.data

您的问题是 URL https://jsonplaceholder.typicode.com/users返回用户数组。 这意味着res.data将导致 users 数组。

数组没有data属性,因此res.data.data将导致undefined 请改用setUsers(res.data)

当前响应具有以下结构:

[ « users » ]

setUsers(res.data.data)仅在响应具有以下结构时才有效:

{ "data": [ « users » ] }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM