【问题标题】:how to show data in JSX in the iteration? [duplicate]如何在迭代中显示 JSX 中的数据? [复制]
【发布时间】:2020-01-30 11:03:34
【问题描述】:

问题是当我 console.log 时变量具有值,但它没有在页面中呈现。循环只打印第一个数据,其他数据不打印。

const langData = [
  {
    name: "Front-End",
    children: [
      {
        name: "HTML"
      },
      {
        name: "CSS"
      },
      {
        name: "JS"
      }
    ]
  }
];
const renderName = ({ name, children }) => {
  console.log(name);
  return (
    <>
      <p>{name}</p>
      {children && children.forEach(newData => renderName(newData))}
    </>
  );
};

const App = () => {
  return <div className="App">{renderName(langData[0])}</div>;
};

例如:前端将在页面上。页面中未显示的其他数据,例如 HTML、CSS、JS。但是这些变量在console.log 中。不确定我是否错过了返回任何值。

代码沙盒链接:https://codesandbox.io/s/reverent-ardinghelli-6snby?fontsize=14

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    渲染一个数组,你应该使用map,因为.forEach总是返回undefined:

    const renderName = ({ name, children, index }) => {
      console.log(name);
      return (
        <div key={index}>
          <p>{name}</p>
          {children && children.map((item, index)=> {
            const { name } = item;
            return renderName({name, index})
          })}
          {/* {children && children.forEach(newData => renderName(newData))} */}
        </div>
      );
    };
    

    【讨论】:

      【解决方案2】:

      使用 map 你可以遍历数组。 map 有效而 forEach 无效的原因是 map 返回一个新数组,而 forEach 不返回任何内容(返回未定义)。您还需要添加键以消除警告。我在这里使用数组的索引作为键:

      const renderName = ({ name, children }, key) => {
        console.log(name);
        return (
          <>
            <div key={key}>
            <p>{name}</p>
            {children && children.map((newData,index) => renderName(newData, index))}
            </div>
          </>
        );
      };
      

      【讨论】:

        【解决方案3】:

        试试这个你会直接得到你的结果。

        import React from "react";
        import ReactDOM from "react-dom";
        
        import "./styles.css";
        const langData = [
          {
            name: "Front-End",
            children: [
              {
                name: "HTML"
              },
              {
                name: "CSS"
              },
              {
                name: "JS"
              }
            ]
          }
        ];
        const renderName = (name,data) => (
          //console.log(name);
          <>
            <p>{name}</p>
            {data && data.map(child => (
              <p>{child.name}</p>
            ))}
          </>
        );
        
        const App = () => {
          return <div className="App">{renderName(langData[0].name,langData[0].children)}</div>;
        };
        
        const rootElement = document.getElementById("root");
        ReactDOM.render(<App />, rootElement);
        

        【讨论】:

          猜你喜欢
          • 2022-01-11
          • 1970-01-01
          • 2018-08-24
          • 2022-06-23
          • 1970-01-01
          • 2020-08-30
          • 1970-01-01
          • 2020-05-13
          • 1970-01-01
          相关资源
          最近更新 更多