与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)
我在做什么错了?
答案 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]);