javascript - React Hook useEffect 缺少依赖项:'location.state'。要么包含它,要么移除依赖数组 react-hooks/exhaustive-deps
问题描述
我已将 id 作为状态一函数传递
<Link
className="title"
id="titles"
to={{
pathname: "/postDetail",
state: { id:story.objectID }
}}
>
{story.title}
</Link>
下面是子函数
const location = useLocation();
const { id } = location.state;
useEffect(() => {
const link = `http://hn.algolia.com/api/v1/items/${id}`
const getPost = async () => {
await fetch(link)
.then((response) => response.json())
.then((data) => {
const post = data;
setPost(post);
setLoading(false);
});
}
getPost();
}, []);
我不知道我做错了什么,有人说要const { id } = location.state;
在 useEffect() 内部移动。我试过了,但它仍然给我同样的错误。该怎么办?
解决方案
尝试这个 :
const location = useLocation();
const { id } = location.state;
useEffect(() => {
const link = `http://hn.algolia.com/api/v1/items/${id}`
const getPost = async () => {
await fetch(link)
.then((response) => response.json())
.then((data) => {
const post = data;
setPost(post);
setLoading(false);
});
}
getPost();
}, [id]);
推荐阅读
- reactjs - 反应上下文状态值未在消费者中更新
- c# - 是否有一个函数可以在 IF 命令中的 String 中创建 OR 函数
- reactjs - 我可以对 @spartacus 框架使用 react 吗?
- c++ - 附加一个空字符串 ostream 可防止进一步附加
- rust - 尽管有足够的信息,但仍需要类型注释
- python - 使用KIVY构建的Android App无法上网
- python - 如何检查子进程是否正在轮询,但未接收数据
- ios - SwiftUI基于设备设置navigationViewStyle
- oracle - Oracle 窗口函数 - 检索元素直到下一次出现值
- ubuntu - 未找到 GLIBC_2.27 Ubuntu 16.04