簡體   English   中英

JSON 對象的 Next.js Typescript 句柄

[英]Next.js Typescript handle of JSON Object

我正在使用 Next.js 和 Typescript 進行個人項目。 我在應用程序默認附帶的 hello.ts 上有一個 API 調用。 我在那里添加了一個JSON文件。 目前,我在映射該JSON並呈現它的內容時遇到問題。 目前, JSON在 useState 中,但是當我嘗試用它做某事時,瀏覽器和控制台會給我錯誤。

這是帶有 msaller JSONhello.ts ,位於/pages/api/hello

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'

type Data = {
  clientName: string
  campaignName: string
  userName: string
  frames: {
    id: string
    asset: string
    subheading: string
    description: string
    link: string
  }[]
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  res.status(200).json({
  userName: "username",
  frames: [
      {
          id: "1",
          asset: "",
          subheading: "Instagram",
          description: "",
          link: "someurl.com"
      },
      {
          id: "3",
          asset: "",
          subheading: "Facebook",
          description: "username Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean sollicitudin metus vitae",
          link: "someurl.com"
      }
  ] })
}

這是我調用位於 api 的components/container的地方:

import { useEffect, useState } from "react";

import { FrameContainerProps } from "../../types";

const FrameContainer: React.FC<FrameContainerProps> = () => {
    const  [apiDetails, setapiDetails] = useState<any>();

    useEffect(() => {
        fetch('http://localhost:3000/api/hello')
          .then((res) => {
            return res.json();
          })
          .then(
            (data) => {
                setapiDetails(data);
            },
            (err) => {
                return console.error(err);
            }
          );
    }, []);

    return (
        <>
            {Object.entries(apiDetails).map(detail => (
                <h3>{detail.frames[i].description ? detail.frames[i].description : ''}</h3>
            ))}
        </>
    )
}

export default FrameContainer;

另外,只有當數據內部有值時,如何才能呈現數據?

apiDetails默認值設置為 null 並添加檢查以查看數據是否已加載。
此外,您應該map apiDetails.frames

import { useEffect, useState } from 'react';

import { FrameContainerProps } from '../../types';

const FrameContainer: React.FC<FrameContainerProps> = () => {
  const [apiDetails, setapiDetails] = useState<any>(null);

  useEffect(() => {
    fetch('http://localhost:3000/api/hello')
      .then((res) => {
        return res.json();
      })
      .then((data) => {
        setapiDetails(data);
      })
      .catch((err) => {
        return console.error(err);
      });
  }, []);

  if (!apiDetails) return <>Loading data...</>;

  return (
    <>
      {apiDetails.frames && apiDetails.frames.map((frame) => (
        <h3>
          {frame.description || ''}
        </h3>
      ))}
    </>
  );
};

export default FrameContainer;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM