【问题标题】:.map json from prisma in component来自组件中棱镜的.map json
【发布时间】:2022-01-04 21:31:00
【问题描述】:

我正在尝试使用来自 prisma 的数据映射 nextjs 类组件中的 json 对象。我对来自 prisma 的数据进行字符串化,否则我会在日期参数上收到序列化错误。

我知道我无法 .map this.props.cmets2,但我如何以正确的方式实现我想要做的事情?

获取数据:

Index.tsx:

export default function Home({ comments2 }) {
...
}

export async function getServerSideProps() {
  console.log("lol");
  const comments = await prisma.casinoComment.findMany();
  const comments2 = JSON.stringify(comments);
  console.log(comments2);
  return { props: { comments2 } };
}

组件/List.tsx:

interface IProps {
  comments2: [
    {
      content: string;
    }
  ];
}

export default class FeaturedCasinos extends React.Component<
  IProps,
  IState,
  { country: String; flag: String }
> {
  constructor(props: IProps) {
    super(props);
  }

  render() {
    return {
    <>
      {this.props.comments2.map((comment, index) => {
        comment.content;
       })}
    </>
    }
  }
  ...
  }

Json 对象:

[
  {
    "id": 1,
    "casinoId": 1,
    "content": "test",
    "reply": false,
    "parentId": 0,
    "approved": false,
    "likes": 3,
    "createdAt": "2021-11-21T19:47:56.387Z",
    "updatedAt": "2021-11-21T19:47:56.387Z",
    "authorId": "ckw87a0r50008hvpvas31ow8k"
  },
  {
    "id": 2,
    "casinoId": 1,
    "content": "test",
    "reply": false,
    "parentId": 0,
    "approved": false,
    "likes": 3,
    "createdAt": "2021-11-21T19:52:07.427Z",
    "updatedAt": "2021-11-21T19:52:07.427Z",
    "authorId": "ckw87a0r50008hvpvas31ow8k"
  }
]

【问题讨论】:

  • 你想做什么?我很困惑
  • 只在组件中.map/输出cmets2中的json对象。

标签: reactjs next.js prisma


【解决方案1】:

不是 100% 回答你的问题,但从外观上看只是改变你的 jsx

这个

    <>
      {this.props.comments2.map((comment, index) => {
        comment.content;
       })}
    </>

到这里

    <>
      {this.props.comments2.map((comment, index) => {
         return(
           <p>comment.content</p>
         )
       })}
    </>

【讨论】:

  • 我试过了,但它返回:TypeError: this.props.cmets2.map is not a function...我怀疑因为我字符串化了“comment”,所以我丢失了对象属性,所以我不能使用 .地图,但我不确定
  • @CultofTranquility 你控制台记录了组件内的comments2 数组吗?
  • 是的,它似乎在那里,但它似乎只是一个带有 json 的字符串,而不是带有 .map 属性的数组或对象。
【解决方案2】:

我解决了...

解决方案是在对 cme​​ts 进行字符串化后对其进行 JSON.parse:

  const comments = await prisma.casinoComment.findMany();

  const comments2 = JSON.stringify(comments);
  const parsedComments = JSON.parse(comments2);

在此 .map 在组件中工作之后,因为您不能 .map 纯字符串(它不是具有 .map 属性的数组或对象)...

【讨论】:

    猜你喜欢
    • 2011-04-02
    • 2020-03-07
    • 2012-03-27
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 2021-11-06
    • 2017-03-26
    相关资源
    最近更新 更多