【问题标题】:I have a problem with the 'getStaticPaths' function. A required parameter (id) was not provided as a string in getStaticPaths我对“getStaticPaths”函数有疑问。在 getStaticPaths 中未将必需参数 (id) 作为字符串提供
【发布时间】:2021-08-26 11:51:39
【问题描述】:

我的“getStaticPaths”函数有问题。在 getStaticPaths 中未将必需参数 (id) 作为字符串提供。连我都用过id:users.id.toString()

export default function usersID({ users }) {
      return (
        <div>
          <h1> {mobile.name} </h1>
        </div>
      );
    }

export const getStaticPaths = async () => {
  const res = await fetch(`http://jsonplaceholder.typicode.com/users`);
  const data = await res.json();

  const paths = data.map((users) => {
    return {
      params: {
        id: users.id.toString()
      },
    };
  });

  return {
    paths,
    fallback: false,
  };
};

export const getStaticProps = async (context) => {
  const id = context.params.id;
  const res = await fetch(`http://jsonplaceholder.typicode.com/users/${params.id}` );
  const data = await res.json();

  return {
    props: { users: data },
  };
};

【问题讨论】:

  • 您确定定义了users 吗?你退出users.id.toString()了吗?
  • 是的!我也尝试过使用其他 API,但仍然显示错误!

标签: reactjs next.js


【解决方案1】:

我没有错误,只是在 getStaticProps 中不是 params.id 而是 id

文件夹结构是

---用户 -----> [id].js

使用 id 2 可从 my_url.example/user/2 访问

//[id].js
import React from "react";

const User = ({ users }) => {
    console.log(users);

    return <div>user</div>;
};

export const getStaticPaths = async () => {
    const res = await fetch(`http://jsonplaceholder.typicode.com/users`);
    const data = await res.json();

    const paths = data.map((users) => {
        return {
            params: {
                id: users.id.toString(),
            },
        };
    });

    return {
        paths,
        fallback: false,
    };
};

export const getStaticProps = async (context) => {
    const id = context.params.id;
    const res = await fetch(`http://jsonplaceholder.typicode.com/users/${id}`);
    const data = await res.json();

    return {
        props: { users: data },
    };
};

export default User;

【讨论】:

    猜你喜欢
    • 2021-12-12
    • 1970-01-01
    • 2021-10-05
    • 2021-09-04
    • 2023-02-12
    • 2021-03-26
    • 2022-07-09
    • 2021-07-10
    • 2019-06-21
    相关资源
    最近更新 更多