首页 > 解决方案 > TypeError:Events.map 不是函数

问题描述

所以我正在使用reactjs,但是当我想用componentdidMount调用我的api时,我在reactjs中很新

class Rank extends Component {
constructor(props){
    super(props);
   this.state = {Events: {}, golfer_events: [] }

}

componentDidMount(){
    fetch('http://localhost/Golfer/api/EventApi/rank?id=2')
    .then(response =>{
            return response.json()   
    })
    .then(json => console.log("json:", json))
    .then(json => this.setState({Events: json.conversation}))

}


render() {
    const {Events} = this.state;
        return (
            <div>
                {
                    Events.map(event =>{
                        const {id, title, golfer} = event;
                        return(
                            <div key ={id}>
                                <Card>
                                    <CardBody>
                                        {title}
                                        {golfer}
                                    </CardBody>
                                </Card>
                            </div>
                            )
                    })
                }
            </div>
        );
    }
}

标签: reactjsrest

解决方案


在构造函数中,您将事件设置为对象而不是数组。对象没有导致问题的地图功能。

 constructor(props){
        super(props);
       this.state = {Events: [] = [], golfer_events: [] = [] }

    }

componentDidMount(){
    fetch('http://localhost/Golfer/api/EventApi/rank?id=2')
    .then(response =>{
            return response.json()   
    })
    .then(json => console.log("json:", json))
    .then(json => this.setState({Events: (json.conversation || [])}))

}

推荐阅读