首页 > 解决方案 > 遍历对象数组并显示项目 [REACT JS]

问题描述

我正在尝试遍历一组对象,在 div 中显示结果,但有些东西没有按预期工作。当我控制台日志时,它似乎检索数据并显示它。

const example =
      {
          "example": [
             {
               "test": "test",
               "img": "img.png",
               "song": "song title"
             },
             {
               "test": "test2",
               "img": "img.png2",
               "song": "song title2"
             }
           ]
         }

     const renderData= () => {
          example.example.forEach(function (arrayItem) {
            const test= arrayItem.test
            const img= arrayItem.img
            const song= arrayItem.song
            
            return (
              <div className="test">
              <div className="test">
                <div className="test">
                  <img
                    src={img}
                    alt="sunil"
                  />
                </div>
                <div className="test">
                    {test}
                    <span className="test">
                    </span>
                  <p>{song}</p>
                </div>
              </div>
            </div>
            );
          });
        };


return (
      <div
     
          {renderData()}
    
      </div>
    );
}

什么都没有出现,但是当我这样做时:

     example.example.forEach(function (arrayItem) {
      var x = arrayItem.test+ arrayItem.img+ arrayItem.song;
      console.log(x);
  });

它工作并控制台正确的信息。

任何人都可以发现错误或提供帮助吗?

请忽略命名约定。

标签: javascriptreactjs

解决方案


JSX.Element您需要from的返回数组renderData。在您的情况下,您返回undefined。返回一个新数组JSX.Elementwith map而不是forEach,它不返回任何内容。

const renderData = () => {
    return example.example.map((arrayItem, i) => {
        const test = arrayItem.test;
        const img = arrayItem.img;
        const song = arrayItem.song;

        return (
            <div key={i} className="test">
                <div className="test">
                    <div className="test">
                        <img src={img} alt="sunil" />
                    </div>
                    <div className="test">
                        {test}
                        <span className="test"></span>
                        <p>{song}</p>
                    </div>
                </div>
            </div>
        );
    });
};

推荐阅读