繁体   English   中英

将对象作为道具传递给子组件

[英]pass object from state as props to child component

我正在用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作为道具传递给子组件,但我收到TypeError:无法读取未定义的属性'data'

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

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

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

这将确保仅在daily初始化时才显示WeeklyWeather

第一个渲染this.state.weather尚未初始化

第一次关注此线程React状态数据为null

   class App extends Component {
      constructor () {
        super()
        this.state = {
          weather: {}
        }
      }

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

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

您是在将道具传递给孩子之前将其传递给孩子。

一旦将HTML绑定到DOM,就会调用componentDidMount() ,这意味着您的render()已经运行。 但是,当然,您的render()引用this.state.weather.daily.data ,直到componentDidMount()完成后才存在。

您要做的就是在尝试使用数据之前检查是否已加载数据。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM