最终返回不会在 React 中渲染

问题描述 投票:0回答:1

我的所有日志中都显示有数据,最初它们是未定义的,但是一旦从道具中检索到数据,它们就会正确显示......但是,它仍然处于加载状态......

我的结构有问题吗:

 import React, { useEffect, useState } from 'react';

    import './styleTopTen.css'; 

    function TopTenView({ topTenData }) {
      const baseUrl = import.meta.env.VITE_MOP_BASE_URL;
      const defaultPic = '/images/pic1.png';

      const [isReady, setIsReady] = useState(false);

      useEffect(() => {
        if (topTenData && Array.isArray(topTenData) && topTenData.length > 0) {
          setIsReady(true);
        }
      }, [topTenData]);

      if (!isReady) {
        return <div>Loading...</div>; // Or null if you don't want to render anything
      }

      console.log('ttv', topTenData);
    console.log('isReady',isReady)
    console.log('after TTV if', topTenData);

      return (
        
        <div className="top-ten-container">
        <div className="title">TOP 10</div>
        <div className="entities-container">
          {topTenData.map((entity, index) => (
            <div key={`top-entity-${index}`} className="entity-circle">
              <img src={entity.entity_pic || defaultPic} alt={entity.entity_name} className="entity-img" />
              <div className="entity-name">{entity.entity_name}</div>
            </div>
          ))}
        </div>
      </div>
      );
    }

    export default TopTenView;

enter image description here

reactjs react-redux
1个回答
0
投票

您的组件“TopTenView”似乎正在接受来自其父组件的道具,因此每次父组件重新渲染该子组件也会重新渲染,因此如果您提供空依赖项数组来实现挂钩,它也可以正常工作。这是我建议的唯一修改,否则你的代码看起来写得很好。

© www.soinside.com 2019 - 2024. All rights reserved.