无法在 NextJS 上获取上下文值

问题描述 投票:0回答:1

我正在尝试从上下文 api 获取值,但是,我得到了一个默认值(没有在上下文调用期间进行的更新)和一个未定义的值(应该在上下文提供程序中获取一个值)

sortListContext.tsx

import React from 'react'
type Props = {
    actualSort?:string;
    sorts:string[];
}
export const SortListContext = React.createContext<Props>({
    sorts: []
})

export function SortListProvider({children}:any){
    const [actualSort, setActualSort] = React.useState<string>()
    const sorts = ['numberAsc','numberDesc','nameAsc','nameDesc']

    function getSort(){
        if(typeof window !== 'undefined'){
            const local = localStorage.getItem('sort')
            if(local){
                return ('A')
            }
            else{
                return ('B')
            }
          }
    }

    React.useEffect(()=>{
        setActualSort(getSort)
    },[])
    
    return (
        <SortListContext.Provider value={{ sorts, actualSort}}> 
            {children}
        </SortListContext.Provider>
    )


}

export function useSortListContext(){
    return React.useContext(SortListContext)
}

收藏夹.tsx

import React from 'react'
import  Container  from '../components/pokedex/container/'
import  Main  from '../components/pokedex/main/'
import  PokemonList  from '../components/pokedex/pokemonList/'
import {useFavoritesContext} from '../contexts/favoritesContext'
import {useSortListContext} from '../contexts/sortListContext'

interface Types  {
  type: {
    name:string;
  }
}

interface PokemonProps {
  id:number;
  name:string;
  types: Types[];
}


const Favorites = () => {
    const {favorites} = useFavoritesContext()
    const {sorts, actualSort} = useSortListContext()

    const [localFavorites, setLocalFavorites] = React.useState<string[]>()
    const [pokemonList, setPokemonList] = React.useState<PokemonProps[]>([])


    React.useEffect(()=>{
      if(typeof window !== 'undefined'){
        console.log(actualSort, sorts)
      }
      

    },[actualSort, sorts])

    React.useEffect(()=>{
      if(localFavorites && localFavorites.length > 0){
          
          localFavorites?.forEach((item)=>{
            async function getPokemon() {
              const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${item}`) 
              const data = await response.json()
    
              setPokemonList((oldPokemonList)=> [...oldPokemonList, data])
              
              
            }
            getPokemon()
            
          })
      }
        
    },[localFavorites])

    React.useEffect(()=>{
      setLocalFavorites(favorites)
      setPokemonList([])
    }, [favorites])

    
      return (
      <Container>
       <Main>
        <PokemonList pokemonList={pokemonList} /> 
       </Main>
       </Container>
      )
    
    
  
}

export default Favorites

我已经尝试为 actualSort 设置初始值但不起作用,错误可能出在提供者上

javascript reactjs next.js react-context next
1个回答
1
投票

我只是忘了用提供商包装我的应用程序,谢谢@YoussoufOumar;这是我使用 Context 的第一个项目。

这是固定的代码_app.tsx

import type { AppProps } from 'next/app';
import GlobalStyle from '../styles/global';

import { FavoritesProvider } from '../contexts/favoritesContext';
import { SortListProvider } from '../contexts/sortListContext';

export default function App({ Component, pageProps }: AppProps) {
    return (
        <>
            <GlobalStyle />
            <FavoritesProvider>
                <SortListProvider>
                    <Component {...pageProps} />
                </SortListProvider>
            </FavoritesProvider>
        </>
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.