【发布时间】:2020-01-18 06:26:54
【问题描述】:
我收到错误“React Hook React.useEffect 缺少依赖项:'openPosts'”,其中 openPosts 是 Hook 中的状态。
export const Posts = (props) => {
const [openPosts, setOpenPosts] = React.useState([]); *openPosts is an array of numbers*
React.useEffect(_ => {
let filteredOpenPosts = openPosts.filter(num => num >= 1);
setOpenPosts(filteredOpenPosts);
}, [props.userId]);
我已经阅读过,但我不明白为什么会出现此错误。我可以忽略它吗?
我本质上希望通过更改props.userId 来过滤状态,并认为这是一种干净的方法。我还可以创建更多状态来跟踪 props.userId 中的任何更改,但如果上述方法可行,我会更喜欢它。
【问题讨论】:
-
openPosts如果/当userId更改时更改的可能性是多少?通过不将openPosts包含为useEffect的依赖项,这仅意味着如果openPosts发生更改,那么除非userId也更新,否则您的useEffect代码将不会重新运行。 -
openPosts每次userId更改时都会更新。您描述的行为是故意的。 -
您好,请检查我的解决方案,如果有帮助,请告诉我。
标签: reactjs react-hooks use-effect