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

时间:2020-05-11 10:45:02

标签: javascript reactjs redux react-redux

与redux相关的导入如下-

来源:https://github.com/theairbend3r/pokedex

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

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


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

我有一个useEffect块,如下所示-

  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)

我在做什么错了?

1 个答案:

答案 0 :(得分:3)

按照建议将pokemonList添加到the dependency array,您的回调取决于pokemonList.length)的值,该值可能会发生变化。

将更新pokemonList时,回调将使用更新的length重新运行。

此外,您无需以it is for cleaning up an effect的身份从useEffect返回。

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

编辑:好像fetchPokemonNameUrl被实现为中间件,您可以将其重写为:

const fetchPokemonNameUrl = async (dispatch) => {
  const response = await axios.get(URL);
  const data = response.data.results;

  data.map(async (poke) => {
    const responseDetails = await axios.get(poke.url);

    let tempDetails = {
      name: responseDetails.data.species.name,
      baseExperience: responseDetails.data.base_experience,
      height: responseDetails.data.height,
      weight: responseDetails.data.weight,
      type: responseDetails.data.types[0].type.name,
      sprites: responseDetails.data.sprites.front_default,
    };

    dispatch(getData(tempDetails));
  });
};

// And call it:
useEffect(() => {
  if (pokemonList.length !== NUMBER_OF_POKEMON) {
    fetchPokemonNameUrl(dispatch);
  }
}, [dispatch,pokemonList]);