首页 > 解决方案 > 如何通过调用 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

标签: javascriptreactjslocal-storage

解决方案


你可以只使用 if 条件。如果 pokemon 未定义,则不需要将 item 设置为 localStorage。

useEffect(() => {
    if (pokemon.pokemon !== undefined) {
        localStorage.setItem('pokemons', JSON.stringify(pokemon.pokemon));
    }
}, [pokemon]);

推荐阅读