【问题标题】:React Hook useEffect has a missing dependency- MobxReact Hook useEffect 缺少依赖项 - Mobx
【发布时间】:2021-05-07 03:27:04
【问题描述】:

我正在使用 mobx 和 react hooks 一起。我有一个 useContext 来获取商店功能

const store = useContext(MyStore)
useEffect(() => {
        if (init !== '') {
            store.loading = true;
            store.bulkApprove(init).then(data => {
                store.unCheckAll();
            });
        }
    }, [init]);

我可以看到下面的一堆警告

 React Hook useEffect has a missing dependency: 'store'. Either include it or remove the dependency array

我真的很困惑,为什么我需要在依赖数组中包含存储

【问题讨论】:

  • 是的,我一直在这条路上。我花了很多时间尝试以一种满足 linter 的方式编写我的钩子...... linter 坚持认为函数中涉及的所有内容也存在于其 dependencies 中。我决定忽略这一点,直到他们更新 linter,我找到另一种更有效地编写我的钩子的方法,或者这成为一个问题。我知道这不是您想要的,但认为它可能会有所帮助。
  • React hook linter 是为了提供指导而构建的,将所有变量添加到依赖项中是一种很好的做法。但是,由您决定挂钩的哪个变量依赖于触发 useEffect 中的重新渲染循环。

标签: javascript reactjs react-hooks mobx


【解决方案1】:

React Hook useEffect has a missing dependency: <dep>. Either include it or remove the dependency array 只是意味着 linter 警告您,您有一个依赖于可能会更改的外部值的依赖项。

store 订阅了上下文MyStore。这意味着它正在跟踪其变化。

【讨论】:

    【解决方案2】:

    如果有人还在看,我在 youtube 上找到了一个可行的解决方案

    https://www.youtube.com/watch?v=0FS3pJa6rME

    您基本上使用上下文包装存储,然后将您的函数包装在观察者中。这个解决方案绕过了我发现自己陷入的语法地狱。

    我的商店是这样的:

       import { observable, decorate, action } from "mobx";
       import { createContext } from "react";
       class NewsFormStore {
         formValues = [];
         onChange = (name, value) => {
           this.formValues[name] = value;
         };
       }
       decorate(NewsFormStore, {
         formValues: observable,
         onChange: action
       });
    
       export const store = new NewsFormStore();
       export const StoreContext = createContext(store);
    
    

    将 store 用于简单的 textField 可以如下所示:

       import React, { useState, useContext } from "react";
       import { observer } from "mobx-react-lite";
       import { StoreContext } from "../../../../Stores/NewsFormStore";
    
       export const OutlinedTextFields = observer(props => {
       const store = useContext(StoreContext);
       const classes = useStyles();
       const [label] = useState(props.label !== "" ? props.label : "");
       const [name] = useState(props.name !== "" ? props.name : "");
    
       return (
    
          <TextField
            value={store.formValues[name]}
            onChange={e => store.onChange(name, e.target.value)}
            onBlur={e => store.onChange(name, e.target.value)}
            label={label}
            name={name}
          />
    
         );
       });
       export default OutlinedTextFields; 
    

    【讨论】:

      猜你喜欢
      • 2021-02-23
      • 2019-10-24
      • 2020-10-26
      • 2020-03-07
      • 2020-02-25
      • 2020-06-11
      • 2020-03-30
      • 2020-12-29
      • 2019-09-20
      相关资源
      最近更新 更多