簡體   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