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

Javascript 如何在react.js中调度操作时在useEffect()中使用if/else,javascript,reactjs,redux,react-redux,Javascript,Reactjs,Redux,React Redux,我的redux相关导入如下所示: useEffect(() => { return dispatch(fetchPokemonNameUrl()) }, [dispatch]) 资料来源: 我有一个useffect块,如下所示- useEffect(() => { return dispatch(fetchPokemonNameUrl()) }, [dispatch]) 我想做的是- useEffect(() => { if (po

我的redux相关导入如下所示:

  useEffect(() => {
    return dispatch(fetchPokemonNameUrl())
  }, [dispatch])
资料来源:

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

  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)

我做错了什么?

口袋妖怪列表
添加到建议中,您的回调取决于
口袋妖怪列表
.length
)的值,该值可能会更改

当更新
pokemonList
时,将使用更新后的
length
再次运行回调

另外,您不需要从
useffect
as返回



Edit:看起来像是作为中间件实现的
fetchpokemonameurl
,您可以像这样重写:

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]);

您需要在依赖项数组中添加pokemonList…即<代码>[dispatch,pokemonList]我尝试了你的解决方案,但我的应用程序现在无法加载。在控制台中,我得到以下-
警告:effect函数不能返回除用于清理的函数之外的任何内容。看起来您编写了useffect(async()=>…)或返回了一个承诺。相反,在您的效果中编写异步函数并立即调用它:
您可以看看这里的代码=>?相关文件是
pokemonCardsSlice.js
PokemonCards.js
fetchPokemonNameUrl
不是一个动作,而是一个中间件。你不能这样叫它看你想试试@dennis Vash吗我宁愿不被否决,那我们怎么称呼它呢?比如,如果我这样做,应用程序就会工作=>`useffect(()=>{dispatch(fetchPokemonNameUrl())},[dispatch])`。
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]);