React Js map 函数给出 "not a function" 错误

React Js map function gives an "not a function" error

我正在尝试映射对象以在我的 React JS 项目中显示它们的值。看起来我无法使用 map 函数访问对象内对象的值,根本不显示值,或者如果我尝试使用 (.split("/p")) 它给我一个错误提示 "split is not a function".

Link to codesandbox

这是我的代码:

import React from "react";
import { studies } from "./studies";

import "./styles.css";

const Data = ({ title, text, number, numberdesc }) => {
  return (
    <>
      <div style={{ margin: "1rem" }}>{title}</div>
      <div style={{ margin: "1rem" }}>{text}</div>
      <div>{number}</div>
      <div>{numberdesc}</div>
    </>
  );
};

function App() {
  const appComponent = studies.map((post, i) => {
    console.log(studies);
    return (
      <Data
        key={i}
        number={studies[i].post.number}
        title={studies[i].post.title}
        text={studies[i].post.text
          .split("/p")
          .reduce((total, line) => [total, <br />, <br />, line])}
      />
    );
  });
  return <>{appComponent}</>;
}

export default App;

{研究}文件:

export const studies = [
  {
    id: "first",
    text: "1st Post",
    post: {
      data: [
        { number: "100", numberdesc: "description1" },
        { number: "200", numberdesc: "description2" },
        { number: "300", numberdesc: "description3" }
      ],

      text: [
        {
          title: "Title1 from the 1st post",
          text: "Text1 from the 1st post."
        },
        {
          title: "Title2 from the 1st post",
          text: "Text2 from the 1st post."
        },
        {
          title: "Title3 from the 1st post",
          text: "Text3 from the 1st post"
        }
      ]
    }
  },
  {
    id: "second",
    text: "2nd Post",
    post: {
      data: [
        { number: "100", numberdesc: "description1" },
        { number: "200", numberdesc: "description2" },
        { number: "300", numberdesc: "description3" }
      ],

      text: [
        {
          title: "Title1 from the 2nd post",
          text: "Text1 from the 2nd post "
        },
        {
          title: "Title2 from the 2nd post",
          text: "Text2 /p from the 2nd post"
        },
        {
          title: "Title3 from the 2nd post",
          text: "Text3 from the 2nd post"
        }
      ]
    }
  }
];

我想要做的是访问每个 post 的 数据和文本 值,并将它们显示在我的项目中。非常感谢任何帮助和建议,

谢谢。

我想您可能想要 .map 您的一系列内容。例如:

text={studies[i].post.text.map(t => <p><strong>{t.title}</strong>: {t.text}</p>)}

可能会替换断线的现有线路。

这是您要找的吗?

function App() {
  const appComponent = studies.map(study =>
    study.post.data.map((data, k) => (
      <Data
        key={k}
        number={data.number}
        numberdesc={data.numberdesc}
        title={study.post.text[k].title}
        text={study.post.text[k].text}
      />
    ))
  );
  return <>{appComponent}</>;
}

请注意,我将 data[k]numbernumberdesc 任意压缩为 text[k]titletext,但这可能不一定是您打算显示的内容。

如果您的 datatext 数组在任何给定 study.

中的长度不同,则上述内容可能会中断

看到了here.