【发布时间】:2020-07-08 23:52:25
【问题描述】:
主要的黄金是从外部 API 制作一个搜索栏。我正在使用 Context API 来提供全局状态,并使用自定义异步挂钩来调用 pokeapi,我目前可用,将搜索到的数据存储在 localstorage 中,但问题是我从状态在事件中发生变化,因此当我重新加载页面时状态未定义,并将本地存储值设置为未定义......有更好的方法来解决这个问题吗?
上下文:
import React,{createContext, useEffect} from 'react'
import { usePokemonReducer } from './PokemonReducer'
import {FIND_POKEMON} from './Actions'
export const PokemonContext = createContext()
const PokemonProvider = ({children}) => {
const [state, dispatch] = usePokemonReducer(()=>{
const localData = localStorage.getItem('pokemons');
return localData ? JSON.parse(localData) : [];
});
const { pokemon } = state;
const findPokemon = (pokemon) => dispatch({ type: FIND_POKEMON, pokemon})
useEffect(() => {
localStorage.setItem('pokemons', JSON.stringify(pokemon.pokemon));
}, [pokemon]);
const providerValues = {
pokemon,
findPokemon,
}
return (
<PokemonContext.Provider value={providerValues}>
{children}
</PokemonContext.Provider>
)
}
export default PokemonProvider;
customAsyncHook:
import {useEffect, useState, useContext} from 'react'
import { PokemonContext } from '../../Services/Store/PokemonContext'
import {FIND_POKEMON} from '../../Services/Store/Actions'
import axios from 'axios'
const useAsyncHook = (id) => {
const [result, setResult] = useState();
const [loading, setLoading] = useState('false');
const { findPokemon } = useContext(PokemonContext)
useEffect(() => {
async function getPokemon() {
try {
setLoading('true');
const response = await axios(
`https://pokeapi.co/api/v2/pokemon/${id}`
);
setResult(response.data);
findPokemon({type:FIND_POKEMON, pokemon:response.data });
} catch (error) {
setLoading('null');
findPokemon({type:FIND_POKEMON, pokemon:null });
}
}
if (id !== "") {
getPokemon();
}
}, [id]);
return [result, loading];
}
export default useAsyncHook
【问题讨论】:
-
我对reactjs不熟悉,但我认为现在不是使用localStorage的合适时机。通常 localStorage 用于保存数据,因此您无需重新查询。这意味着您的页面将从本地存储中读取而不是进行查询,但我在您的代码中看不到任何看起来正在发生的事情。
标签: javascript reactjs local-storage