尝试映射数组时出错...无法读取未定义的属性“map”[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我一直试图理解为什么我在试图映射TypeError: Cannot read property 'map' of undefined时得到this.state.forecastData ..我一直在摆弄并尝试不同的东西,但我不想让它映射。

有人能指出我正确的方向并描述我做错了什么吗? (我在ReactJS的学习阶段)

我可以console.log(res)然后我在控制台得到这个:enter image description here

这是我的组件:

import React, { Component } from 'react';
var queryString = require('query-string');
var api = require('../utils/api');

class Forecast extends Component {
    constructor(props) {
        super(props);

        this.state = {
            forecastData: [],
            loading: false
        }

        this.makeRequest = this.makeRequest.bind(this);
    }

    componentDidMount () {
        this.city = queryString.parse(this.props.location.search).city;
        this.makeRequest(this.city);
    }

    componentWillReceiveProps(nextProps) {
        this.city = queryString.parse(nextProps.location.search).city;
        this.makeRequest(this.city);
    }

    makeRequest (city) {
        this.setState(function () {
            return {
                loading: true,
            }
        })

        api.getCurrentWeather(city)
      .then(function (res) {
                console.log(res)
                this.setState(function () {
                    return {
                        forecastData: res,
                        loading: false,
                    }
                })
            }.bind(this))
    }

    render() {
    return this.state.loading === true
      ? <h1 className='forecast-header'> Loading </h1>
      : <div>
                    <h1 className='forecast-header'>{this.city}</h1>
                    <div className='forecast-container'>
                        {this.state.forecastData.list.map(function (listItem) {
                            return <div>Test</div>
                        }, this)}
                    </div>
                </div>
     }
}

export default Forecast;
javascript reactjs
1个回答
0
投票
{this.state.forecastData.list.map(function (listItem) {
                        return <div>Test</div>
                    }, this)}

应该

{this.state.forecastData.map(function (listItem) {
                            return <div>Test</div>
                        }, this)}

因为你正在访问listforecastData,但forecastData已经是你可以映射的阵列了。

© www.soinside.com 2019 - 2024. All rights reserved.