gpt4 book ai didi

javascript - 当尝试将数组传递到 React 中的子组件时,得到了未定义的映射

转载 作者:行者123 更新时间:2023-11-28 16:59:29 25 4
gpt4 key购买 nike

我是 React 新手,正在使用 Open Weather 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

最佳答案

this.state.title[1]this.state.title[0]undefined 直到您创建 GET 请求。

在尝试映射未定义值或添加状态初始值之前,您应该添加一个条件:

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 (默认启用),您可以避免将每个函数绑定(bind)到 this (这很容易出错)。

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

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

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

关于javascript - 当尝试将数组传递到 React 中的子组件时,得到了未定义的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57970047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com