【问题标题】:React.useEffect missing dependency - stateReact.useEffect 缺少依赖项 - 状态
【发布时间】: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


【解决方案1】:

如果你不想指定依赖,那么你可以试试这个,

React.useEffect(_ => {
    setOpenPosts(prevState => prevState.filter(num => num >= 1));
}, [props.userId]);

【讨论】:

    猜你喜欢
    • 2020-01-06
    • 2017-12-25
    • 2015-04-18
    • 2020-03-24
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多