我的 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)
我究竟做错了什么?
最佳答案
按照建议将 pokemonList
添加到 the dependency array,您的回调取决于 pokemonList
( .length
) 的值,该值可能会改变。
当 pokemonList
更新时,回调将使用更新后的 length
再次运行。
此外,您不需要从 useEffect
返回 it is for cleaning up an effect 。
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]);
关于javascript - 在 react.js 中调度 Action 时如何在 useEffect() 中使用 if/else,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61727815/