首页 > 解决方案 > 我对“getStaticPaths”函数有疑问。在 getStaticPaths 中未将必需参数 (id) 作为字符串提供

问题描述

我对“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 },
  };
};

标签: reactjsnext.js

解决方案


我这边没有错误,只是在 getStaticProps 它不是params.id而是id

文件夹结构是

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

可以从 my_url.example/user/2 访问使用 id 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;

推荐阅读