簡體   English   中英

如何從json數據動態渲染reactjs組件

[英]how to dynamically render reactjs components from json data

我有一些json數據。 3個不同的對象。 我想從這些對象中獲取數據並將其呈現在屏幕上。 基本上每個對象都有一個名稱、摘要和圖標。 所以我想查看所有 3 個對象並在屏幕上顯示每個圖標、名稱和摘要。 這些對象是特色應用程序。 它們顯示在網格中。 每個應用程序都有自己的徽章。 徽章位於 AppBadgeHomePage.js 文件中。

現在什么都沒有渲染。 我得到了 h3 標簽,就是這樣。 有一個用於“特色”的 div 類,但下面沒有任何內容。 似乎this.state.feat.map壞了。 或不工作。 或者可能是這樣,並且沒有任何內容傳遞給應用程序徽章。 我在另一個文件中調用特色應用程序網格就好了。 我只是想知道這是否是我太累並且盯着它看太久的情況之一。

json 數據看起來像這樣。 圖標和摘要位於 customData 對象中。

{
 name: appName,
 customData: {
     icon: iconURL,
     summary: summary
  }
 }

市場.js

import AppBadgeHomePage from './AppBadgeHomePage';
import React, { Component } from 'react';

export default class FeaturedGrid extends React.Component {
    
    constructor(props){
        super(props);
        this.getFeaturedApps = this.getFeaturedApps.bind(this);
        let name, summary, icon;
    }
    
    state = {
        feat: []
    }

    getFeaturedApps = () => {
        fetch(`http://localhost:3001/apps/featured`)
        .then(response => response.json())
        .then(responseJson => {
            this.setState({
                feat: responseJson.map(item => ({
                    name: item.name,
                    icon: item.customData.icon,
                    summary: item.customData.summary
                }))
            })
        })
    }
    render(){
        return (
            <div>
                <h3>Featured Apps</h3>
                    <div className="featured">
                        {this.state.feat.map(featured => (
                            <AppBadgeHomePage 
                                name={featured.name}
                                icon={featured.customData.icon}
                                summary={featured.customData.summary}
                            />
                        ))}
                    </div>
            </div>
        )
    }
}

AppBadgeHomePage.js

import React, { Component } from 'react';

export default class AppBadgeHomePage extends React.Component {
    
    render(){
        return (
            <a className="featured-grid-item-badge" href="www.google.com">
                <div className="featured-grid-item">
                    <img className="featured-appIcon" src={this.props.icon} />
                        <div>
                            <p className="featuredTitle">{this.props.name}</p>
                        </div>
                        <div>
                            <p className="badgeSummary">{this.props.summary}</p>
                        </div>
                </div>
            </a>
        )
    }
}

你為什么要映射 feat,feat 應該是一個數組

嘗試這個 :-

 getFeaturedApps = () => {
    fetch(`http://localhost:3001/apps/featured`)
    .then(response => response.json())
    .then(responseJson => {
        this.setState({
            feat: responseJson
            }))
        })
    })
}

首先,你需要在render方法下console.log(this.state.feed)查看feed數組是否一直為空。

如果它是空白的,那么我建議您在 componentDidMount() 方法中調用 API。

如果它不是空白,那么您會注意到提要狀態具有您已經將其設置為所需鍵值對的對象,因此無需這樣做:

<AppBadgeHomePage 
   name={featured.name}
   icon={featured.customData.icon}
   summary={featured.customData.summary}
/>

而是這樣做:

<AppBadgeHomePage 
   name={featured.name}
   icon={featured.icon}
   summary={featured.summary}
/>

總而言之,如果沒有渲染子組件,則數組必須一直為空。 如果正在呈現子組件並且值未顯示,則調用的鍵是錯誤的。

從反應文檔:

構造函數

避免在構造函數中引入任何副作用或訂閱。 對於這些用例,請改用componentDidMount()

  1. 數據獲取應該從componentDidMount生命周期方法分派。
  2. 不要在類體中混合使用constructor初始化狀態。
  3. getFeaturedApps是一個箭頭函數,因此不需要在構造函數中將this綁定到它。
  4. 您應該檢查承諾鏈中的成功fetch 您還應該處理來自返回的承諾鏈的承諾拒絕和其他拋出的錯誤。
  5. 在映射this.state.feat您錯誤地嘗試訪問原始嵌套值,但是在提取響應處理中映射時,您將特征元素展平了。

代碼:

class FeaturedGrid extends React.Component {
  state = {
    feat: []
  };

  componentDidMount() {
    this.getFeaturedApps();
  }

  getFeaturedApps = () => {
    fetch(`http://localhost:3001/apps/featured`)
      .then((response) => {
        if (!response.ok) {
          throw new Error('Response not ok');
        }
        return response.json();
      })
      .then((responseJson) => {
        this.setState({
          feat: responseJson.map((item) => ({
            name: item.name,
            icon: item.customData.icon,
            summary: item.customData.summary
          }))
        });
      })
      .catch(console.error);
  };

  render() {
    return (
      <div>
        <h3>Featured Apps</h3>
        <div className="featured">
          {this.state.feat.map((featured) => (
            <AppBadgeHomePage
              name={featured.name}
              icon={featured.icon}
              summary={featured.summary}
            />
          ))}
        </div>
      </div>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM