使用 AppProviderContext.Provider 时找不到命名空间“AppProviderContext”

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

当我尝试返回时找不到命名空间“AppProviderContext”

<AppProviderContext.Provider
      value={{
        rooms,
        members,
        selectedRoom,
        isAddRoomVisible,
        setIsAddRoomVisible,
        selectedRoomId,
        setSelectedRoomId,
        isInviteMemberVisible,
        setIsInviteMemberVisible,
        clearState,
      }}
    >
      {children}
    </AppProviderContext.Provider>

我还为此提供了板条箱接口和上下文,但是我无法使用 AppProvideContext,我不知道为什么???请救救我

interface AppContextType {
  rooms: Room[];
  members: Member[];
  selectedRoom: Room;
  isAddRoomVisible: boolean;
  setIsAddRoomVisible: Dispatch<SetStateAction<boolean>>;
  selectedRoomId: string;
  setSelectedRoomId: Dispatch<SetStateAction<string>>;
  isInviteMemberVisible: boolean;
  setIsInviteMemberVisible: Dispatch<SetStateAction<boolean>>;
  clearState: () => void;
}

const AppProviderContext = createContext<AppContextType | undefined>(undefined);

我正在尝试使用

return (
    <AppProviderContext.Provider
      value={{
        rooms,
        members,
        selectedRoom,
        isAddRoomVisible,
        setIsAddRoomVisible,
        selectedRoomId,
        setSelectedRoomId,
        isInviteMemberVisible,
        setIsInviteMemberVisible,
        clearState,
      }}
    >
      {children}
    </AppProviderContext.Provider>
  );
firebase react-native
1个回答
0
投票

我相信你忘记了一些配置 参考:https://mobileledge.medium.com/usecontext-in-react-native-andbest-practices-1e899dc0f802

试试这个方法

import React, {createContext, useContext, ReactNode} from 'react';

interface AppContextType {
  room: string; //replace with type of value you wanted
}

const AppProviderContext = createContext<AppContextType | undefined>(undefined);

export const useAppHelper = () => {
  const context = useContext(AppProviderContext);
  if (!context) {
    throw new Error('useAppHelper must be used within an AppProviderContext');
  }
  return context;
};

interface AppProviderProps {
  children: ReactNode;
}

export const AppProvider = ({children}: AppProviderProps) => {
  const room = 'value';
  return (
    <AppProviderContext.Provider
      value={{
        room,
      }}>
      {children}
    </AppProviderContext.Provider>
  );
};

© www.soinside.com 2019 - 2024. All rights reserved.