简体   繁体   English

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

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

I am creating weather app with React and I have an api which provides me object 我正在用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>
    );
  }
}

After fetching it, I store data as state. 提取数据后,我将数据存储为状态。 Finally, I want to pass this.state.weather.daily.data as props to child component, but I received TypeError: Cannot read property 'data' of undefined 最后,我想将this.state.weather.daily.data作为道具传递给子组件,但我收到TypeError:无法读取未定义的属性'data'

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

It can be you get the error because before the async request has finished, there is no this.state.weather.daily initialized. 可能是您收到错误,因为在异步请求完成之前,没有this.state.weather.daily初始化。 Quick hack could be something like this: 快速黑客可能是这样的:

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

This will make sure WeeklyWeather is only rendered when daily is initialized. 这将确保仅在daily初始化时才显示WeeklyWeather

the first render this.state.weather isn't initialized yet 第一个渲染this.state.weather尚未初始化

follow this thread React state data null for the first time 第一次关注此线程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>
        )
      }
    }

You're passing the prop to the child before it exists. 您是在将道具传递给孩子之前将其传递给孩子。

componentDidMount() is called once the HTML is bound to the DOM, which means your render() has already run. 一旦将HTML绑定到DOM,就会调用componentDidMount() ,这意味着您的render()已经运行。 But, of course, your render() refers to this.state.weather.daily.data which doesn't exist until after componentDidMount() completes. 但是,当然,您的render()引用this.state.weather.daily.data ,直到componentDidMount()完成后才存在。

All you have to do is check that the data is loaded before you attempt to use it. 您要做的就是在尝试使用数据之前检查是否已加载数据。

<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