ReactJS TypeError: Undefined 不是一个函数(near'..用户.地图..')



我是React的新手,正在尝试学习它。我正在从API获取数据,我将使用这些数据。它只是返回数组列表数据。请帮我解决这个问题,日志说它来自JSX中的users.map循环。我想在用户常量上显示数据,并成为数组列表

const Item = ({user_id, title, body}) => {
return (
<View style={styles.container}>
<Text style={styles.text}>User Id :{user_id}
</Text>
<Text style={styles.text}>Tittle :{title}
</Text>
<Text style={styles.text}>Body :{body}
</Text>
<View style={styles.line}></View>
</View>
)
}

const Berita = () => {
const [users,
setUsers] = useState([]);
useEffect(() => {
getData();
}, []);
const getData = () => {
axios
.get('https://gorest.co.in/public/v1/posts')
.then(res => {
console.log('res: ', res);
setUsers(res.data);
})
}
return (
<View style={styles.container}>
{users.map(user => {
return <Item 
key={user.id} 
user_id={user.user_id} 
title={user.title} 
body={user.body}/>
})}
</View>
)
}
export default Berita

感谢您抽出时间

您应该执行以下操作:

const getData = () => {
axios
.get('https://gorest.co.in/public/v1/posts')
.then(res => {
setUsers(res.data.data); // <-- change to `res.data.data`
});
}

你的问题是res.data不是你想象的那样。它实际上是一个对象,而不是一个数组,所以当试图在对象上使用.map()时,你会得到一个错误,因为.map()不是对象的方法p。

当使用axios.get()时,您会得到一个Promise,它解析为一个具有以下形状的响应对象:

请求的响应包含以下信息。

{
// `data` is the response that was provided by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the HTTP headers that the server responded with
// All header names are lower cased and can be accessed using the bracket notation.
// Example: `response.headers['content-type']`
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {},
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance in the browser
request: {}
}

在您的示例中,.then(res =>中的res是此结构的对象,而此响应对象的data属性保存API响应的主体/数据。在您的示例中,上面对象的data属性包含:

{
"meta": {
/* ... properties ... */
},
"data": [/* user objects */ {...}, {...}, ...]
}

因此,要从对象对象正确访问用户对象数组,您首先需要访问res.data,它允许您访问上述对象,然后访问.data(通过使用res.data.data(,以便从对象访问用户对象阵列。

最新更新