[英]Why won't my array use the map method even though it's actually an array?
So I console.log the state of users after I set it as an array of objects from the github api and it displays as an array.因此,在我将用户的 state 设置为来自 github api 的对象数组后,我 console.log 记录它并显示为数组。 However, I can't use the map function like this (if I decided to use it in a child component using props):
但是,我不能像这样使用 map function (如果我决定在使用道具的子组件中使用它):
this.state.users.map((user)=>(
<UserItem key={user.id} user={user}/>
))
I get an error: "TypeError: this.state.users.map is not a function" And It's pretty confusing because it is an array.我收到一个错误:“TypeError:this.state.users.map 不是函数”而且它很混乱,因为它是一个数组。 It looks like this in the props viewer:
在道具查看器中看起来像这样:
As you can see.
如你看到的。 Users is an array.
用户是一个数组。 I don't understand but I could be missing something very simple from lack of coffee.
我不明白,但我可能会因为缺乏咖啡而错过一些非常简单的东西。 Thanks for your help.
谢谢你的帮助。 I appreciate it.
我很感激。
import React, { Component } from 'react';
import Navbar from './components/layout/Navbar';
// import UserItem from './components/users/UserItem';
import Users from './components/users/Users';
// import './App.css';
import axios from 'axios';
class App extends Component {
state = {
users: {},
loading: false
}
async componentDidMount() {
this.setState(
{loading: true}
)
const res = await axios.get('https://api.github.com/users')
this.setState(
{
loading: false,
users: res.data,
}
)
// console.log(res.data)
}
render() {
return (
<React.Fragment>
<Navbar />
<div className="container">
<Users loading={this.state.loading} users={this.state.users} />
</div>
</React.Fragment>
);
}
}
export default App;
The initial value of this.state.users
is an object. this.state.users
的初始值为 object。 Hence the error map is not a function
因此错误
map is not a function
state = {
users: {}, <--- object
loading: false
}
The API call happens after the component has mounted for the first time in the componentDidMount
life cycle method and the value of state.users
gets populated with the data. API 调用发生在组件在
componentDidMount
生命周期方法中首次挂载之后,并且state.users
的值被填充了数据。
The component has to render with the initial state on the first render.该组件必须在第一次渲染时使用初始 state 进行渲染。
Change the value of users
to be an empty array in the initial state.在初始 state 中将
users
的值更改为空数组。
state = {
users: [], // change initial value of users to be an empty array
loading: false
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.