我想首先在页面加载以及单击按钮时使用自定义钩子加载数据。
每次单击时,记录数量应增加一个固定数字。 问题是,我的钩子将导致永久性重新渲染导致的无限循环。 我该如何使用自定义钩子解决这些问题?
function useLoadPokemon(increaseTo) {
const [pokemonState, setPokemonState] = useState([]);
const [amount, setAmount] = useState(increaseTo);
const apolloClient = new useApolloClient(getApolloContext());
useEffect(() => {
function load() {
const getPokemon = gql`
query pokemons($recordCount: Int!){
pokemons(first:$recordCount) {
name,
image
}
}
`;
apolloClient.query({
query: getPokemon,
variables: {
recordCount: amount,
},
})
.then((pokemon => {
setPokemonState(pokemon.data.pokemons);
}));
}
load();
}, [amount])
const loadPokemon = function(){
setAmount(amount + amount);
}
return [{ pokemonState }, loadPokemon];
}
function ShowPokemon() {
let [{ pokemonState }, loadPokemon] = useLoadPokemon(5);
// ...
<input type="button" value="Lade mehr..." onClick={() => { loadPokemon();}}></input>
错误消息:
错误:重新渲染过多。 React限制了渲染次数以防止无限循环。