在 useEffect 中调用 Redux Action

Call a Redux Action inside a useEffect

我这里的objective是在useEffect.

里面调用一个action
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)

它工作正常,但我收到警告

React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array  react-hooks/exhaustive-deps.

但是如果我要在 useEffects 中添加 props 作为我的第二个参数,那么它将无休止地 运行。

我的第一个解决方法是使用 useRef,但它似乎总是会重新渲染,因此会再次重新设置 useRef,我认为这在优化方面并不好。

const ref = useRef();
  ref.current = props;
  console.log(ref)


  useEffect(()=>{
  ref.current.fetchTodos()
  },[])

这里还有其他解决方法吗?

您必须将 fetchTodos 添加到依赖项中。

const ShowTodos = ({ fetchTodos }) => {
  useEffect(() => {
    fetchTodos();
  }, [fetchTodos])
  ...
}

或者像这样。

const ShowTodos = (props) => {
  const { fetchTodos } = props;

  useEffect(() => {
    fetchTodos();
  }, [fetchTodos])
  ...
}

这是一个 eslint 警告,如果 useEffect 中的任何依赖项不是依赖项数组的一部分,您会收到该警告。

在您的情况下,您在 useEffect 中使用 props.fetchTodos 并且 eslint 警告提示您提供 props 作为依赖项,以便如果 props 发生变化,useEffect 函数会从其闭包中获取更新的 props .

但是,由于 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)

然而,您可以在不禁用规则的情况下解决问题,例如

const ShowTodos = (props) =>{
   const { fetchTodos } = props
   useEffect(()=>{
     fetchTodos()
   },[fetchTodos])
} 

不过,我会建议您知道应该在什么时候禁用规则或将值传递给依赖项数组。