我正在尝试使用开放天气 API 来显示天气。带有对象的 api 响应。我有一个状态
state = {
cityWeather: {},
}
在 api 响应中,我将该响应设置为 cityWeather;这是在天气主要组件中完成的
const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&ApiKey=2747592557924542516e283a7f905a81`;
axios.get(url).then((response) => {
const weatherData=response.data;
this.setState(()=>({ cityWeather:weatherData}));
我得到的回复是
{coord: {…}, weather: Array(1), base: "stations", main: {…}, wind: {…}, …}
base:"stations"
clouds :{all: 48}
cod:200
coord: {lon: 10.74, lat: 59.91}
dt:1536870000
id:3143244
main: {temp: 13, pressure: 1010, humidity: 66, temp_min: 13, temp_max: 13}
name:"Oslo"
sys:
{type: 1, id: 5325, message: 0.0038, country: "NO", sunrise: 1536813716, …}
weather : [{…}]
wind : {speed: 5.7, deg: 220}}
现在,我想从父组件将此 cityWeather 数据作为 Prop 传递给其子组件 CurrentWeathe
<CurrentWeather data={this.state.cityWeather}/>
现在,当我访问子组件中的 props 时,React 会抛出此错误
{this.props.data.name} //this line works
{this.props.data.wind.speed} //this give me error saying Uncaught TypeError: Cannot read property 'speed' of undefined. because wind is object inside the main object.
我的问题是如何将这些嵌套对象作为 Prop 传递。
如果我单独设置所有值而不是对象,这是可行的,但是我如何立即将这些单独的值作为 prop 传递。
最佳答案
该错误是因为如果你的 api 需要一些时间来响应(这是正常的),那么组件将首先在没有值的情况下渲染,在获取值后它将再次渲染(如果 this.setState() 或 this.forceUpdate() 是称为)。
因此,在第一次渲染时,Child 将在没有值的情况下渲染,因此它将通过这样的错误来克服这个问题,我们可以给出不同的返回值
- 如果没有数据
- 获取数据后
在CurrentWeather的render方法中改为此
render(){
if(!this.props.data.name){
return(
<div>
Loading....
</div>
)
}else {
return (
.....//Your current return code for CurrentWeather class (component)
.....
)
}
}
关于javascript - 我如何在 react 中将嵌套对象作为 Prop 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52322079/