【问题标题】:API function call not working in react component [closed]API函数调用在反应组件中不起作用[关闭]
【发布时间】:2020-05-12 07:06:43
【问题描述】:

我从 API 获取数据的功能不起作用

import React, { Component } from 'react'

class Contact extends Component{

    constructor(){
        super()
        this.state = {
            data: []
        }
        this.fetchData = this.fetchData.bind(this)
    }

    fetchData(){
        let base_url = 'https://jsonplaceholder.typicode.com/photos/'
        fetch(base_url, {method:"GET"})
        .then(response => response.json())
        .then(json => {
            this.setState({
                data:json
            })
        })

        console.log(this.state.data)
    }

    render(){
        return(
            <div>
                <h1>Contact page{this.state.data.title}</h1>
            </div>
        )
    }
}

export default Contact

【问题讨论】:

  • 请添加更多详细信息,例如您收到的错误消息等
  • 可能你必须使用地图功能,因为你的状态“数据”是数组

标签: javascript reactjs react-router fetch-api


【解决方案1】:

首先,您没有在任何地方调用fetchData 函数。在componentDidMount 方法中调用它

其次,数据应该是一个数组,所以this.state.data.title 会抛出你可以错误

最后状态更新反映在下一个渲染周期中,因此记录 console.log(this.state.data) 不会显示更新的数据

    class Contact extends React.Component{
    
        constructor(){
            super()
            this.state = {
                data: []
            }
            this.fetchData = this.fetchData.bind(this)
        }
    
        componentDidMount() {
           this.fetchData();
        }
    
        fetchData(){
            let base_url = 'https://jsonplaceholder.typicode.com/photos/'
            fetch(base_url, {method:"GET"})
            .then(response => response.json())
            .then(json => {
                this.setState({
                    data:json
                })
            })
    
        }
    
        render(){
            return(
                <div>
                    <h1>Contact page</h1>
                    {this.state.data.map(photo => <div>{photo.title}</div>)}
                </div>
            )
        }
    }
    
    ReactDOM.render(<Contact/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 2021-09-22
    • 1970-01-01
    • 2021-11-21
    • 2021-12-11
    • 1970-01-01
    • 2021-09-15
    相关资源
    最近更新 更多