the*_*d3r 3 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)
Run Code Online (Sandbox Code Playgroud)
我有一个useEffect块如下 -
useEffect(() => {
return dispatch(fetchPokemonNameUrl())
}, [dispatch])
Run Code Online (Sandbox Code Playgroud)
我想做的事 -
useEffect(() => {
if (pokemonList.length !== NUMBER_OF_POKEMON) {
return dispatch(fetchPokemonNameUrl())
}
}, [dispatch])
Run Code Online (Sandbox Code Playgroud)
但当我这样做时,我收到警告 -
React Hook useEffect has a missing dependency: 'pokemonList.length'. Either include it or remove the dependency array.eslint(react-hooks/exhaustive-deps)
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
按照建议添加pokemonList到依赖项数组中,您的回调取决于pokemonList( .length) 的值,该值可能会发生变化。
当pokemonList更新时,回调将使用更新后的length.
另外,您不需要返回,useEffect因为它是为了清理效果。
useEffect(() => {
if (pokemonList.length !== NUMBER_OF_POKEMON) {
dispatch(fetchPokemonNameUrl());
}
}, [dispatch,pokemonList]);
Run Code Online (Sandbox Code Playgroud)
编辑:似乎是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]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1946 次 |
| 最近记录: |