javascript - 将对象从 state 作为 props 传递给子组件

标签 javascript reactjs state

我正在使用 React 创建天气应用程序,并且我有一个为我提供对象的 api

import React, { Component } from 'react';
import WeeklyWeather from './components/WeeklyWeather';
const api = '';
class App extends Component {
  constructor() {
    super();
    this.state = {
      weather: {}
    }
  }

  componentDidMount() {
    fetch(api)
    .then(response => response.json())
    .then(data => this.setState({ weather: data }));
  }

  render() {
    return (
      <div className="App">
        <WeeklyWeather day={this.state.weather.daily.data} />
      </div>
    );
  }
}

获取数据后,我将数据存储为状态。 最后,我想将 this.state.weather.daily.data 作为 props 传递给子组件,但我收到了 TypeError: Cannot read property 'data' of undefined

最佳答案

    <WeeklyWeather day={this.state.weather.daily.data} />

您可能会收到错误,因为在异步请求完成之前,没有初始化 this.state.weather.daily。快速破解可能是这样的:

  {   this.state.weather.daily && <WeeklyWeather day={this.state.weather.daily.data} />}

这将确保 WeeklyWeather 仅在初始化 daily 时呈现。

关于javascript - 将对象从 state 作为 props 传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53804900/

相关文章:

reactjs - 在功能组件中使用 REST Api 调用更新 React Context

javascript - MERN 堆栈 : Using Redux to store whether user is logged in or not

android - 是否可以创建用于 StateListDrawable 的自定义状态?

javascript - 如果页面内容改变高度,向上/向下滑动页脚

javascript - 范围选择器不显示

node.js - 我需要将用户输入作为获取请求的一部分提交给 unsplash 服务器

javascript - react odoo 的 native 应用程序

ios - 如何知道 iOS 设备是否在后台进程中休眠

php - 如何将 PHP 值传递给外部 JavaScript 文件

javascript - react 函数中的类激活