[英]Call a Redux Action inside a useEffect
My objective here is to call an action inside a useEffect
. 我的目标是在
useEffect
调用一个动作。
const ShowTodos = (props) =>{
useEffect(()=>{
props.fetchTodos()
},[])
}
const mapStateToProps = (state)=>{
return {
todos:Object.values(state.todos),
currentUserId:state.authenticate.userId
}
}
export default connect(mapStateToProps,{fetchTodos})(ShowTodos)
It works fine but I got a warning 它工作正常,但我收到了警告
React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array react-hooks/exhaustive-deps.
But if I'm going to add props
as my second parameter in my useEffects
then it will run endlessly. 但是,如果我要在我的
useEffects
添加props
作为我的第二个参数,那么它将无休止地运行。
My first workaround here is to use the useRef
but it seems that it will always re-render thus re-setup again the useRef which I think is not good in terms of optimization. 我在这里的第一个解决方法是使用
useRef
但它似乎总是重新渲染,因此重新设置useRef,我认为在优化方面不好。
const ref = useRef();
ref.current = props;
console.log(ref)
useEffect(()=>{
ref.current.fetchTodos()
},[])
Is there any other workaround here ? 这里还有其他解决方法吗?
That is an eslint
warning that you get if any of the dependency within useEffect
is not part of the dependency array. 如果
eslint
任何依赖useEffect
不是依赖项数组的一部分,那么这是一个eslint
警告。
In your case you are using props.fetchTodos
inside useEffect and the eslint warning prompts you to provide props
as a dependency so that if props changes, the useEffect function takes the updated props from its closure. 在你的情况下,你在useEffect中使用
props.fetchTodos
,并且eslint警告提示你提供props
作为依赖项,这样如果props更改,useEffect函数将从其闭包中获取更新的props。
However since fetchTodos
is not gonna change in your app lifecycle and you want to run the effect only once you can disable the rule for your case. 但是,由于
fetchTodos
在您的应用程序生命周期中不会发生变化,并且您只想在禁用案例规则后运行该效果。
const ShowTodos = (props) =>{
const { fetchTodos } = props
useEffect(()=>{
fetchTodos()
// eslint-disable-next-line import/no-extraneous-dependencies
},[])
}
const mapStateToProps = (state)=>{
return {
todos:Object.values(state.todos),
currentUserId:state.authenticate.userId
}
}
export default connect(mapStateToProps,{fetchTodos})(ShowTodos)
You however can solve the problem without disabling the rule like 但是,您可以在不禁用规则的情况下解决问题
const ShowTodos = (props) =>{
const { fetchTodos } = props
useEffect(()=>{
fetchTodos()
},[fetchTodos])
}
I however will recommend that you know when exactly should you disable the rule or pass the values to the dependency array. 但是,我建议您知道何时应该禁用规则或将值传递给依赖关系数组。
You have to add fetchTodos to dependencies. 您必须将fetchTodos添加到依赖项。
const ShowTodos = ({ fetchTodos }) => {
useEffect(() => {
fetchTodos();
}, [fetchTodos])
...
}
or like this. 或者像这样。
const ShowTodos = (props) => {
const { fetchTodos } = props;
useEffect(() => {
fetchTodos();
}, [fetchTodos])
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.