【问题标题】:How to loop and render elements in React after we got the data from the backend?从后端获取数据后,如何在 React 中循环和渲染元素?
【发布时间】:2022-01-10 15:06:36
【问题描述】:

如何遍历后端的数据并基于它渲染组件?

我尝试过这样的事情:

import React, { useEffect } from 'react';
import BuildingItem from './components/buildingItem';
import { Config } from './config/config';

export default function Buildings() {

  const buildings = [];

  useEffect(() => {
    fetch(Config.domain + 'kingdom/buildings', {
      headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }
    })
      .then(res => res.json())
      .then(data => {
        
        for(let i = 0; i < data.length; i++) {
          buildings.push(<BuildingItem type={data[i].type} level={data[i].level} />);
        }
      })
  })

  return (
    <div className='buildings'>
      <div className='buildings-container'>
        {buildings}
      </div>
    </div>
  );
}

返回时也尝试过这样的事情

<div className='buildings-container'>
        {buildings.map((item)=> (
              item
        )}
</div>

【问题讨论】:

    标签: reactjs react-native loops jsx


    【解决方案1】:

    尝试改变这样的事情。事情是将项目推送到const buildings = [] 没有效果。所以你需要使用useState钩子

    import React, { useEffect, useState } from 'react';
    import BuildingItem from './components/buildingItem';
    import { Config } from './config/config';
    
    export default function Buildings() {
    
      const [buildings, setBuildings] = useState([]);
    
      useEffect(() => {
        fetch(Config.domain + 'kingdom/buildings', {
          headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }
        })
          .then(res => res.json())
          .then(data => setBuildings(data))
      })
    
      return (
        <div className='buildings'>
          <div className='buildings-container'>
            {buildings.map((item)=> (
              <BuildingItem type={item.type} level={item.level} />
            )}
          </div>
        </div>
      );
    }
    

    【讨论】:

      【解决方案2】:

      在此处使用状态,然后对其进行映射。

      而不是这个:

       .then(data => {
              
              for(let i = 0; i < data.length; i++) {
                buildings.push(<BuildingItem type={data[i].type} level={data[i].level} />);
              }
            })
      

      使用 React.useState,例如:const [data, setData] = useState() 而不是 const buildings = [];

       .then(data => {
             // create state like this for example: const [data, setData] = useState() instead of const buildings = [];
            setData(data)
        })
      

      然后在 jsx 中做这样的事情:

      {
      data.map((item, idx) => <BuildingItem type={item.type} level={item.level} />)
      }
      

      【讨论】:

        猜你喜欢
        • 2017-07-20
        • 1970-01-01
        • 2013-09-22
        • 2021-12-09
        • 2016-03-14
        • 1970-01-01
        • 2021-01-02
        • 1970-01-01
        • 2018-01-02
        相关资源
        最近更新 更多