React Native:具有React Navigation v5错误的上下文提供程序:undefined不是对象正在评估'_ref4.navigation'

问题描述

我想使用contextAPI提供状态管理并响应App.js中的navigaton v5。 但是useContext的返回状态是不确定的,我已经搜索了很多,在大多数情况下,包装应用程序组件可以解决问题,但在我的情况下却没有,请问有人可以确定问题吗? 这是App.js

import { Provider as AuthProvider } from "./app/context/AuthContext";
import { Context as AuthContext } from "./app/context/AuthContext";

const Stack = createStackNavigator();

function App() {
  const { state } = React.useContext(AuthContext);
  console.log(state);
  return (
    <NavigationContainer>
      <Stack.Navigator>
        {state.token === null ? (
          <>
            <Stack.Screen
              options={{ headerShown: false }}
              name="Auth"
              component={authFlow}
            />
          </>
        ) : (
          <Stack.Screen
            options={{ headerShown: false }}
            name="Home"
            component={homeFlow}
          />
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default () => {
  return (
    <AuthProvider>
      <App />
    </AuthProvider>
  );
};

这是AuthContext.js


const authReducer = (state,action) => {
  switch (action.type) {
    case "add_error":
      return { ...state,errorMessage: action.payload };
    case "signin":
      return { errorMessage: "",token: action.payload };
    case "signout":
      return { token: null,errorMessage: "" };
    case "clear_error_message":
      return { ...state,errorMessage: "" };
    default:
      return state;
  }
};

const signin = (dispatch,{ navigation }) => {
  return async ({ username,password }) => {
    try {
      const response = await textApi.post("/login/",{ username,password });
      await AsyncStorage.setItem("token",response.data.token);
      dispatch({ type: "signin",payload: response.data.token });
      navigation.navigate("Profile");
    } catch (err) {
      dispatch({
        type: "add_error",payload: "Something went wrong with the sign in",});
    }
  };
};

export const { Provider,Context } = createDataContext(
  authReducer,{ signin,signout,signup,clearErrorMessage,tryLocalSignin },{ token: null,errorMessage: "" }
);

这是createDataContext.js

import React,{ useReducer } from "react";

export default (reducer,action,defaultValue) => {
  const Context = React.createContext();

  const Provider = ({ children }) => {
    const [state,dispatch] = useReducer(reducer,defaultValue);

    const boundActions = {};

    for (let key in action) {
      boundActions[key] = action[key](dispatch);
    }

    return (
      <Context.Provider value={{ state,...boundActions }}>
        {children}
      </Context.Provider>
    );
  };

  return { Context: Context,Provider: Provider };
};

我没有发布完整的代码,但是我认为问题出在上面,代码类似于此处的React Native Authentication With ContextAPI

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)