reactjs - 我对“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 },
};
};
解决方案
我这边没有错误,只是在 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;
推荐阅读
- python - Pandas .resample 获取平均值
- python - 如何连接不同数据库(mysql和postgres)的两个数据框并使用python将输出作为csv文件?
- java - JPA 中的 PostgreSQL 函数 array_agg
- html - 如何在div顶部对齐输入中的文本
- r - 写入 Sharepoint 的 R 脚本
- jquery - 灰色提交按钮在页面加载时不起作用
- javascript - 禁止命令 discord.js v12
- python - python - 模拟模块和方法
- flutter - 在颤振上使用 get_it 对抗循环依赖?
- python - 如何在 peewee-orm 中使用 ThreadPoolExecutor 处理数据库连接池?