简体   繁体   English

UseEffect - React Hook useEffect 缺少依赖项:

[英]UseEffect - React Hook useEffect has a missing dependency:

I'm getting the following error on the useeffect hook.我在 useeffect 挂钩上收到以下错误。

React Hook useEffect has a missing dependency: 'currentPage'. React Hook useEffect 缺少依赖项:“currentPage”。 Either include it or remove the dependency array.eslintreact-hooks/exhaustive-deps包含它或删除依赖项 array.eslintreact-hooks/exhaustive-deps

Any ideas on why I'm getting this?关于为什么我得到这个的任何想法?

const Pagination = () => {
const [ page, setPage ] = useState(1);

let params = new URLSearchParams(window.location.search);
let currentPage = params.get('page') || 1;

useEffect(() => {
    setPage(currentPage)
}, []);

return (
    <div>
        <h1>{page}</h1>
        {/* 
        *
        * Skip number, current page, totalCount
        *                
        */}
    </div>
);

} }

adding currentPage to the dependency array would remove the warning and since the value will not change unless the url changes, usseEffect will effectively be called only once.将 currentPage 添加到依赖项数组将删除警告,并且由于除非 url 更改,否则该值不会更改,因此 usseEffect 只会有效地调用一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM