javascript - 如何通过调用 ReactJS 中的外部 API 来处理本地存储?
问题描述
主要的黄金是从外部 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;
自定义异步钩子:
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
解决方案
你可以只使用 if 条件。如果 pokemon 未定义,则不需要将 item 设置为 localStorage。
useEffect(() => {
if (pokemon.pokemon !== undefined) {
localStorage.setItem('pokemons', JSON.stringify(pokemon.pokemon));
}
}, [pokemon]);
推荐阅读
- python - 使用 ElementTree 解析 XML 数据(NONE 或无数据)
- java - 如何使用内部区域?
- javascript - 如何制作具有该功能的滑块(html、css、js)
- entity-relationship - 我们是否在实体关系图中考虑数据库整个生命周期的全部/部分参与?
- java - 在特定时间使用警报管理器
- python - 创建列表列表,其中每个元素的长度在另一个列表中定义
- awk - 按强制顺序按特定元素过滤文件
- laravel - Laravel:如何对请求使用多个验证规则
- python - 来自多个集合的组合,其中每个结果只有每个集合中的一个元素
- javascript - 每次重新加载页面时,如何从浏览器本地存储中更新 TODO 列表的值?