在react.js中调度动作时如何在useEffect()中使用if / else

我与redux相关的导入如下-

import { useDispatch, useSelector } from "react-redux"

import {
  fetchPokemonNameUrl,
  NUMBER_OF_POKEMON,
  selectorPokemon,
} from "./pokemonCardsSlice"


const dispatch = useDispatch()
const pokemonList = useSelector(selectorPokemon)

I have a useEffect block as follows -

  useEffect(() => {
    return dispatch(fetchPokemonNameUrl())
  }, [dispatch])

我想做的事 -

 useEffect(() => {
    if (pokemonList.length !== NUMBER_OF_POKEMON) {
      return dispatch(fetchPokemonNameUrl())
    }
  }, [dispatch])

但是当我这样做时,我会收到警告-

React Hook useEffect has a missing dependency: 'pokemonList.length'. Either include it or remove the dependency array.eslint(react-hooks/exhaustive-deps)

我究竟做错了什么?

评论
  • 苍老师
    苍老师 回复

    Add pokemonList to the dependency array as suggested, your callback depends on the value of pokemonList (.length) which may change.

    When pokemonList will be updated, the callback will run again with the updated length.

    Also, you don't need to return from useEffect as it is for cleaning up an effect.

    useEffect(() => {
      if (pokemonList.length !== NUMBER_OF_POKEMON) {
        dispatch(fetchPokemonNameUrl());
      }
    }, [dispatch,pokemonList]);
    
  • 冷血动物
    冷血动物 回复

    问题是您在依赖项数组中缺少pokemonList。

     useEffect(() => {
        if (pokemonList.length !== NUMBER_OF_POKEMON) {
          dispatch(fetchPokemonNameUrl())
        }
      }, [pokemonList, dispatch])
    

    更好的方法是像这样包含数组 (编辑)

     let length = pokemonList.length
     useEffect(() => {
        if (pokemonList.length !== NUMBER_OF_POKEMON) {
          dispatch(fetchPokemonNameUrl())
        }
      }, [length, dispatch])