【问题标题】:Getting error: cannot read property 'map' of undefined using Fetch in React?出现错误:无法在 React 中使用 Fetch 读取未定义的属性“地图”?
【发布时间】:2021-07-14 18:34:02
【问题描述】:

我正在尝试使用 React 中的 fetch 映射 JSON 数据,但我的 map 语句出现错误。我做错了什么?


class Carbon extends Component {
    constructor() {
        super()
        this.state = {
            data: []
        }
    }

    render() {
        return (
            <div>
                <h5>Co2 Emissions</h5>
                <h5>Co2 Per Capita</h5>
                {this.state.data.map(data => data.data)}
            </div>
        )
    }
    componentDidMount() {
        fetch('https://raw.githubusercontent.com/owid/co2-data/master/owid-co2-data.json')
            .then( resp => resp.json())
            .then((data)=> {
                this.setState({
                    data: data.url
                })
                console.log(data)
            })
    }
}

export default Carbon

【问题讨论】:

  • 当你尝试map() 时,这意味着this.state.dataundefined。很可能,fetch()componentDidMount() 中返回的data 没有属性url。您可以尝试将其记录到控制台。

标签: json reactjs fetch


【解决方案1】:
{this?.state?.data?.map(data => data?.data)}

你的 data.url 响应可能不是一个数组,我猜这就是它抛出错误的原因,你可以试试这个,它应该可以工作并且不会抛出错误

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 2019-02-22
    • 2021-09-20
    • 2018-12-15
    • 2019-03-14
    • 2014-09-02
    • 2017-06-21
    • 2023-02-20
    相关资源
    最近更新 更多