【问题标题】:pass object from state as props to child component将状态中的对象作为道具传递给子组件
【发布时间】:2019-05-17 05:03:18
【问题描述】:

我正在使用 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

【问题讨论】:

  • 你需要使用setState来更新初始状态(不是this.state.weather = {.......})。能发下相关代码吗?
  • 好的,给我3分钟,我会提供完整代码

标签: javascript reactjs state


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:
        <WeeklyWeather day={this.state.weather.daily.data} />
    

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

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

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

    【讨论】:

      【解决方案3】:

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

      关注这个话题 React state data null for the first time

         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>
              )
            }
          }
      

      【讨论】:

      • 我们现在真的开始投票了吗?伊兰汉堡,giorgim
      猜你喜欢
      • 2017-04-30
      • 2017-11-19
      • 2020-10-08
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 2021-10-15
      相关资源
      最近更新 更多