尝试在React中将数组传递给子组件时得到未定义的映射

时间:2019-09-17 08:14:03

标签: javascript reactjs

我是React的新手,并且正在与Open Weather Map一起创建天气应用程序。我想要实现的是将天数组传递给子组件,然后使用map函数在子组件数组中呈现天。这是我正在使用的代码:

import React, { Fragment, Component } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import SearchBox from "./Containers/SearchBox/SearchBox";
import Header from "./Components/Header/Header";
import styles from "./App.module.css";
import CardContainer from "./Containers/CardContainer/CardContainer";
import axios from "axios";
class App extends Component {
  state = {
    title: []
  };

  getTitle(title) {
    axios
      .get(
        `http://api.openweathermap.org/data/2.5/forecast?q=${title}&APPID=7ad09d078633b652ecef8587a337639e&units=metric`
      )
      .then(res => { //Here I am retrieving data from JSON file received from server
        this.setState(prevState => ({
          title: [...prevState.title, res.data.city.name] //Here I want to access data about name of city
        }));
        this.setState(prevState => ({
          title: [...prevState.title, res.data.list] //This is list array containing days with certain forecast
        }));
      });
  }

  render() {
    return (
      <div className="App">
        <Fragment>
          <Header title={"Weather App"} />
          <div className="container">
            <SearchBox getRequest={this.getTitle.bind(this)} />
          </div>
          <h1 className={styles.cityWeather}>{this.state.title[0]}</h1>
          <CardContainer weatherData={this.state.title[1]} /> //Here I am passing that array of days into child component
        </Fragment>
      </div>
    );
  }
}

export default App;

import React from "react";
import CardItem from "./CardItem/CardItem";

const CardContainer = ({ weatherData }) => {
  return (
    <main>
      {weatherData.map(day => { //HERE I AM GETTING ERROR
        return <p>{day}</p>;
      })}
    </main>
  );
};

export default CardContainer;

enter image description here

1 个答案:

答案 0 :(得分:3)

this.state.title[0]undefined都是GET,直到您提出map请求为止。

您应先添加条件,然后再尝试state未定义值或添加const CardContainer = ({ weatherData }) => ( <main>{weatherData && weatherData.map(day => <p>{day}</p>)}</main> ); // Or adding an initial value class App extends Component { state = { title: ['initial1', 'initial2'] }; .... } 初始值:

this

还要注意,通过使用babel's arrow functions as class properties(默认启用),可以避免将每个函数绑定到// Avoid <SearchBox getRequest={this.getTitle.bind(this)} /> // Using class arrow function: class App extends Component { getTitle = title => { .... }; // use this.getTitle(...) without binding } (容易出错)。

{{1}}