我总是使用来自 npx create-react-app my-app --template typescript。.
function App() {
const [text, setText] = useState('');
const dispatch = useDispatch();
const _someFunction = useCallback(async () => {
try {
dispatch(actionB(dataB))
} catch (error) {
//
}
}, [dispatch]); <- here 2
useEffect(() => {
console.log('text : ', text);
dispatch(actionA(dataA));
_someFunction();
}, [text, dispatch, _someFunction]); <- here 1
return (
<div className="App">
hello
</div>
);
}
export default App;
在'这里1',我可以理解'文本'必须存在于useEffect的[]中,因为它是触发useEffect的变化因素。
对于'dispatch',它不是变化因素,所以我认为它不需要放在[]中。对于'_someFunction'也是如此。
但是,如果我不把'dispatch'和'_someFunction'放在里面,控制台会警告我这样的情况:-。
React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array react-hooks/exhaustive-deps
另外,我知道使用 "dispatch "和"_someFunction "时 // eslint-disable-next-line react-hooks/exhaustive-deps
useEffect里面可以抑制警告。
我想知道正确的方法。我的问题是:-
// eslint-disable-next-line react-hooks/exhaustive-deps
排除其他不需要的依赖关系,例如'dispatch'、'_someFunction'。如果警告是有原因的! 如果所需的东西使你无法实现你所需要的东西,你只是使用了一个错误的模式!
为什么你不在中间再加一个函数,避免使用Effect呢?
const onChange=(value)=>{
setText(value);
dispatch(actionA(dataA));
_someFunction();
}
useEffect是用来随时更新整个组件的。
好吧,你可以这样做!重要的是你不要使用hook。重要的是,你不要使用一个普通函数作为第一个参数,而是使用一个钩子。
useEffect(() => {
console.log("text : ", text);
}, [text]);
const dispatchCallback = useCallback(() => {
dispatch(actionA(dataA));
}, [actionA, dataA]);
useEffect(dispatchCallback, [text]);
useEffect(_someFunction, [text]);
你看,每个效果都是独立的 每当变量文本变化时,你都会调用回调。
我不推荐这种模式! 太多的钩子,而且不是很有用!