首页 > 解决方案 > 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() 内部移动。我试过了,但它仍然给我同样的错误。该怎么办?

标签: javascriptreactjsapireact-routerreact-hooks

解决方案


尝试这个 :

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]);

推荐阅读