【问题标题】:Uncaught TypeError: this.props.forecast.map is not a function未捕获的 TypeError:this.props.forecast.map 不是函数
【发布时间】:2022-01-25 05:28:29
【问题描述】:

我是新来的反应,已经看到一些类似的问题,但还没有找到为什么会发生这种情况。我收到“未捕获的 TypeError:this.state.data.map 不是函数”。这是代码。请帮忙找出问题所在。

  import React from "react";
    
    class Forecast extends React.Component {
        render() {
            const forecastItems = this.props.forecast.map((f) => {
                const url = `http://openweathermap.org/img/wn/${f.wather[0].img}@2x.png`;
                let ampm = 'AM';
                let hour = new Date(f.dt * 1000).getHours();
    
                if (hour > 12) {
                    hour = hour - 12;
                    ampm = 'PM';
                }
                return (
                    <div className="forecast-item">
                        <p className="forecast-item__hour">{hour}:00 {ampm}</p>
                        <p className="forecast-item__temp">{f.temp}</p>
                        <img src={url} alt={f.weather[0].description}/>
                        <p className="forecast-item__description">{f.wather[0].main}</p>
    
                    </div>
                );
            });
            return (
                <div className="forecast">
                {forecastItems}
        </div>);
        }
    }
    
    export default Forecast;

这是父公司,我使用我的代码获取天气 api,它似乎做的一切都是正确的。

import React from "react";
import './App.css';
import SearchMenu from "./Components/search-menu/search-menu";
import CurrentWeather from "./Components/current-weather/current-weather";
import Forecast from "./Components/forecast-weather/forecast-weather";

import {getCurrentWather, getForecast} from './Components/api/weather.api';

class App extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            location: "",
            temp: "",
            feelsLike: "",
            description: "",
            img: "",
            hourlyForecast: ""
        };
    }

    onInputChange(e) {
        this.setState({
            location: e.target.value
        });
    }

    async onFormSubmit() {
      const weatherRes = await getCurrentWather(this.state.location);
      const lat = weatherRes.data.coord.lat;
      const lon = weatherRes.data.coord.lon;
      const forecastRes = await getForecast (lat,lon);

        this.setState({
            temp: weatherRes.data.main.temp,
            feelsLike: weatherRes.data.main.feels_like,
            description: weatherRes.data.weather[0].main,
            img: weatherRes.data.weather[0].img,
            hourlyForecast: forecastRes.data.hourly
                });
            }
    render() {
        return (
            <div className="App">
                <header className="App-header">
                    <SearchMenu
                        location={this.state.location}
                        inputChange={(e) => this.onInputChange(e)}
                        formSubmitted={() => this.onFormSubmit()}
                        />
                    <CurrentWeather
                        currentTemperature={this.state.temp}
                        feelsLike={this.state.feelsLike}
                        description={this.state.description}
                        img={this.state.img}
                    />
                    <Forecast forecast={this.state.hourlyForecast} />
                </header>
            </div>
        );
    }
    }


export default App;

【问题讨论】:

  • 从您的代码分享更多登录信息。例如你在哪里使用这个组件?以及您要向该组件发送什么道具?
  • 我用这个来获取天气api
  • 分享与该组件相关的片段。因为我认为您没有将预测作为数组传递。
  • 添加父组件

标签: javascript reactjs


【解决方案1】:

我觉得应该是下面这样, 我猜您将 hourlyForecast 作为数组映射函数不理解的字符串传递并引发类型错误。

import React from "react";
import './App.css';
import SearchMenu from "./Components/search-menu/search-menu";
import CurrentWeather from "./Components/current-weather/current-weather";
import Forecast from "./Components/forecast-weather/forecast-weather";

import {getCurrentWather, getForecast} from './Components/api/weather.api';

class App extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            location: "",
            temp: "",
            feelsLike: "",
            description: "",
            img: "",
            hourlyForecast: []
        };
    }

    onInputChange(e) {
        this.setState({
            location: e.target.value
        });
    }

    async onFormSubmit() {
      const weatherRes = await getCurrentWather(this.state.location);
      const lat = weatherRes.data.coord.lat;
      const lon = weatherRes.data.coord.lon;
      const forecastRes = await getForecast (lat,lon);

        this.setState({
            temp: weatherRes.data.main.temp,
            feelsLike: weatherRes.data.main.feels_like,
            description: weatherRes.data.weather[0].main,
            img: weatherRes.data.weather[0].img,
            hourlyForecast: Array.isArray(forecastRes.data.hourly) ? forecastRes.data.hourly : [forecastRes.data.hourly]
                });
            }
    render() {
        return (
            <div className="App">
                <header className="App-header">
                    <SearchMenu
                        location={this.state.location}
                        inputChange={(e) => this.onInputChange(e)}
                        formSubmitted={() => this.onFormSubmit()}
                        />
                    <CurrentWeather
                        currentTemperature={this.state.temp}
                        feelsLike={this.state.feelsLike}
                        description={this.state.description}
                        img={this.state.img}
                    />
                    <Forecast forecast={this.state.hourlyForecast} />
                </header>
            </div>
        );
    }
    }


export default App;

【讨论】:

  • 这里我们应该确定预测,因为 prop 是一个数组,并且问题与组件状态无关。
  • 非常感谢,它有帮助,但现在又出现了一个错误“forecast-weather.js: 9 Uncaught TypeError: Cannot read properties of undefined (reading '0')”
  • 您能否在此处记录一个 forecastRes.data.hourly 的示例输出,我们可以确定可能是什么问题
  • 你能不能在 rest 调用下面使用类似的东西来查看相同 const forecastRes = await getForecast (lat,lon); 的输出是什么? console.log(forecastRes.data.hourly);
  • @Ankit ,我添加了原木的照片
【解决方案2】:

在构造函数中初始化你的状态,如下所示

...
this.state = {
            location: "",
            temp: "",
            feelsLike: "",
            description: "",
            img: "",
            hourlyForecast: []
        };

不同的是,hourlyForecast 现在是一个空数组,而不是一个空字符串。

【讨论】:

  • 非常感谢,它有帮助,但现在又出现了一个错误“forecast-weather.js: 9 Uncaught TypeError: Cannot read properties of undefined (reading '0')”
【解决方案3】:

您在父组件中使用字符串初始值设置hourlyForecast 的状态,而不是数据数组。您应该设置如下状态:

this.state = {
 ...
 hourlyForecast: []
};

【讨论】:

  • 非常感谢,它有帮助,但现在又出现了一个错误“forecast-weather.js: 9 Uncaught TypeError: Cannot read properties of undefined (reading '0')”
  • 你还是会出错? @DenisPrudnikov
猜你喜欢
  • 2017-07-20
  • 2019-09-26
  • 2015-12-29
  • 2021-09-09
  • 2017-07-31
  • 2016-11-02
  • 2016-08-07
  • 2016-11-21
  • 2021-03-13
相关资源
最近更新 更多