来自getStaticProps的数据没有显示在NextJS的页面中(但在道具中) [英] data from getStaticProps not showing in page (but is in props) with NextJS

查看:5
本文介绍了来自getStaticProps的数据没有显示在NextJS的页面中(但在道具中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用NextJS从API调用呈现文本时遇到了问题。基本上,我发出一个外部HTTP请求来获取一些模拟数据。模拟数据通过getStaticProps方法以组件上的道具的形式返回。在我的JSX中,我通过{pros.data...}循环访问道具。为简洁起见,我将展示下面的代码。

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
import * as React from "react";
import { useState, useEffect, useCallback, memo } from "react";
import { GetStaticProps } from "next";

type Props = {
  props: {
    data: {}[];
  };
};

const Form: React.NamedExoticComponent<
  | React.RefAttributes<React.Component<{}, any, any>>
  | { children?: React.ReactNode }
> = memo((props) => {
  const [formData, setFormData] = useState({ username: "", password: "" });

  const handleSubmit = (e) => {
    e.preventDefault();
  };

  const handleSetFormData = useCallback(
    (e) => {
      setFormData({
        ...formData,
        [e.target.name]: e.target.value,
      });
    },
    [formData]
  );

  return (
    <>
      <form
        onSubmit={handleSubmit}
        style={{
          display: "flex",
          flexFlow: "column nowrap",
          justifyContent: "center",
          alignItems: "center",
          height: "100vh",
        }}
      >
        <input onChange={handleSetFormData} type="text" name="username" />
        <input onChange={handleSetFormData} type="text" name="password" />
        <button onSubmit={handleSubmit} type="submit">
          Submit
        </button>
      </form>
      {props.data.map((data) => {
        return (
          <ul key={data.id}>
            <li style={{ color: "red", fontSize: "24px" }}>{data.completed}</li>
            <li>{data.title}</li>
          </ul>
        );
      })}
    </>
  );
});

type GetStaticPropsTypeInterface = {
  props: {
    data: {}[];
  };
};

export const getStaticProps: (
  props: React.PropsWithChildren<GetStaticPropsTypeInterface>
) => Promise<{ props: { data: any } }> = (props) => {
  return fetch("https://jsonplaceholder.typicode.com/todos")
    .then((res) => res.json())
    .then((res) => {
      return {
        props: { data: res },
      };
    });
};

export default Form;

生成的HTML如下所示...

推荐答案

代码看起来没有问题,所以我猜该问题可能与其他原因有关。

我的感觉是您可能将表单组件放在componentssrc目录中。Next.js仅在pages目录中查找,并在服务器端呈现这些页面。

下面是一个虚拟示例--如果在pages目录之外使用此getStaticProps函数,会发生什么情况 https://codesandbox.io/s/strange-feather-odg7x?file=/pages/index.tsx

因此,解决方案是在pages/somePage.tsx中获取数据,然后像这样转发道具<Form data={props.data}...

这篇关于来自getStaticProps的数据没有显示在NextJS的页面中(但在道具中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆