我正在使用 mobx 和 react 钩子在一起。 我有一个使用上下文来获取存储函数
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
我真的很困惑为什么我需要在依赖数组上包含存储
React Hook useEffect has a missing dependency: <dep>. Either include it or remove the dependency array
只是意味着 linter 警告您有一个依赖于可能更改的外部值的依赖项。
store
订阅上下文MyStore
。这意味着它正在跟踪其更改。
如果有人还在找,我在 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);
将存储用于简单的 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;