this.props.array.map 不是函数

我正在学习反应,并试图在我定义的数组中为每个用户呈现一个元素,当我去测试它时,我的浏览器会抛出一个错误,说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}/>

        </>

    }


FFIVE
浏览 358回答 3
3回答

牛魔王的故事

this.props.array.map is not a function当您尝试映射不是数组的东西时发生axios.get('/api/users')&nbsp; &nbsp; &nbsp; &nbsp; .then(results =>{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; users: results.data&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; })确保results.data是数组

皈依舞

由于您的状态中有多个值,因此在这种情况下您不希望覆盖其他值chosenUser:undefined。这就是为什么您需要在设置users.您的初始状态为空Array,但Axios返回一个JSON对象,这意味着您将用户的值设置为对象。您的代码应如下所示。componentDidMount(){&nbsp; &nbsp; axios.get('/api/users')&nbsp; &nbsp; .then(results =>{&nbsp; &nbsp; &nbsp; &nbsp; this.setState({...this.state, users: [...this.state.users, results.data]&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; })&nbsp; &nbsp; .catch(err => {&nbsp; &nbsp; &nbsp; &nbsp; console.log(err);&nbsp; &nbsp; });}您可以使用您的map()函数循环遍历每个项目。

紫衣仙女

map()方法仅适用于数组,我认为您调用的 api 的结果不会返回数组。所以,this.props.users不会是一个数组,它会抛出那个错误。我建议检查您调用的 api (/api/users) 并查看结果。它应该是一个数组
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript