【问题标题】:forEach not working in ReactJs while using data from array [duplicate]使用数组中的数据时,forEach 在 ReactJs 中不起作用 [重复]
【发布时间】:2021-11-06 00:06:06
【问题描述】:

我在学习 reactJS 时遇到了一个问题。在这里,我有一个 HomePage 组件,当我试图从定义的数组中获取数据时,forEach 在 ReactJs 中不起作用。下面是代码:

import React, { useEffect } from "react";
import ChessRankings from "../components/ChessRankings";
import "../App.css";


import gifPath from "../assets/pieceChess.gif";

const paraContent = [

"ChessMania is a website that gives the latest update for chess. Chess is one of the 
most tactical games played across the globe. Here our main focus is to present the 
various chess articles. However, this website also covers the basics of learning 
objectives of chess as well as current chess rankings at the international level.",

"Subsequently, we also cover the common FAQs related to chess, the notation, and the 
type of game played in chess. You also get a glimpse of various prestigious 
tournaments of chess played across the globe within a chess calendar and about the 
esteemed players taking part in, it.",

"The last section takes you through the profile of any Lichess Player that loves 
chess. The profile section displays the basic introduction, including name, 
nationality, followers, and total games played. Later it shows the player's rating in 
each variant and the percentage of wins and losses. It also shows the chess variant 
played by that user most and which are least. Finally, it shows the statistics of the 
player in the puzzle section.",

];

const HomePage = () => {
  useEffect(() => {
     document.title = "ChessMania - Home";
  }, []);

return (
<>
  <h1>Hello , Welcome to Chess Mania</h1>
  <br />
  <div className="text-center">
    <img src={gifPath} alt="gif" />
  </div>
  <hr />

  {
    paraContent.forEach((element) => {
    //console.log(element);
    return (<p className="about-paragraph">{element}</p>)
     })
  }

  
    </>
  );
};

 export default HomePage;

我无法找出错误?有谁请告诉我这里有什么问题?

【问题讨论】:

  • forEach() 返回undefined,如果这给了你提示
  • 但是控制台正在打印数组的内容
  • @MohitMaroliyaB17CS036 — 那么? forEach总是返回undefined,这是它应该返回的。
  • 所以我应该从那里删除 return @Quentin
  • 不,你不应该使用forEach。

标签: javascript arrays reactjs for-loop foreach


【解决方案1】:

在渲染元素中使用map函数:

https://codesandbox.io/s/react-code-slr6e

paraContent.map((element, index) => {
    //console.log(element);
    return (<p className="about-paragraph" key={index}>{element}</p>)
})

【讨论】:

  • key 丢失
  • 添加密钥后仍无法正常工作
  • 更新了我的答案以添加密钥
  • 我是这样做的: paraContent.map((item,key) => { return(

    {item}

    ) })
猜你喜欢
  • 2019-12-15
  • 2017-06-03
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
  • 2017-02-10
  • 1970-01-01
  • 2018-03-11
  • 1970-01-01
相关资源
最近更新 更多