[英]Got map of undefined when tried to pass array into children component in React
我是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;
在您發出GET
請求之前, this.state.title[1]
和this.state.title[0]
是undefined
。
您應在嘗試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的箭頭函數用作類屬性 (默認情況下啟用),可以避免將每個函數綁定到this
函數(容易出錯)。
// Avoid <SearchBox getRequest={this.getTitle.bind(this)} />
// Using class arrow function:
class App extends Component {
getTitle = title => {
....
};
// use this.getTitle(...) without binding
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.