我正在学习反应,并试图在我定义的数组中为每个用户呈现一个元素,当我去测试它时,我的浏览器会抛出一个错误,说this.props.users.map不是一个函数,我已经完成了在我不明白我错过了什么之前,与此类似的事情。
在父组件中
constructor(props){
super(props);
this.state = {
users:[],
chosenUser:undefined
}
this.currentUser = this.currentUser.bind(this);
}
componentDidMount(){
axios.get('/api/users')
.then(results =>{
this.setState({
users: results.data
});
})
.catch(err => {
console.log(err);
});
}
render(){
return <>
<Users users={this.state.users} chosenUser={this.state.chosenUser}/>
</>
}
在子组件中
render(){
return<>
<h1>Users rendered</h1>
{this.props.users && this.props.users.map(user =>{<li key={user._id}><button onClick={() => this.props.chosenUser}>{user.name}</button></li> // generate a button for each user
})}
<p>Not on the list? Don't worry, were not super exclusive, you can make a character here!</p>
<NewUserForm newUser={this.addNewUser} name={this.state.name}/>
</>
}
牛魔王的故事
皈依舞
紫衣仙女
相关分类