【问题标题】:Got map of undefined when tried to pass array into children component in React尝试将数组传递给 React 中的子组件时得到未定义的映射
【发布时间】:2019-09-17 08:14:03
【问题描述】:

我是 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;

【问题讨论】:

  • 对 getTitle() 方法使用箭头函数 getTitle = title => {} 那么你不必绑定这个
  • 你的weatherData 可能是undefined。试试Array.isArray(weatherData) &amp;&amp; weatherData.map(...)
  • weatherData={this.state.title[1]} 你是只传递一个标题还是标题数组

标签: javascript reactjs


【解决方案1】:

this.state.title[1]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']
  };
  ....
}

另请注意,通过使用babel's arrow functions as class properties(默认启用),您可以避免将每个函数绑定到this(容易出错)。

// Avoid <SearchBox getRequest={this.getTitle.bind(this)} />
// Using class arrow function:

class App extends Component {
  getTitle = title => {
     ....
  };

  // use this.getTitle(...) without binding
}

【讨论】:

  • 嘿,丹尼斯,谢谢您的友好回答,请在第一个代码块中将天气更改为 weatherData。另外,我读到 getTitle = title => { .... };也不是最佳实践。我应该只使用构造函数来绑定处理程序吗?或者用你建议的就可以了
  • 相反-使用构造函数是一种不好的做法(忘记superbind,不使用生命周期,忘记超级中的props等等),避免它。尝试使用箭头函数和类属性(就像你使用的 state
猜你喜欢
  • 1970-01-01
  • 2019-08-16
  • 2023-02-01
  • 2021-07-25
  • 1970-01-01
  • 2019-08-14
  • 2019-03-22
  • 2021-09-27
  • 2021-10-04
相关资源
最近更新 更多