使用react Context(Ionic-React)时未定义history.push()[重复]

Posted

技术标签:

【中文标题】使用react Context(Ionic-React)时未定义history.push()[重复]【英文标题】:history.push() is undefined when using react Context (Ionic-React) [duplicate] 【发布时间】:2021-05-17 09:02:50 【问题描述】:

UseHistory Hook 在尝试推送到另一个页面时显示未定义,同时尝试在异步函数之后以编程方式导航

上下文

import React,  createContext, useContext, useReducer, useState  from "react";
import AuthReducer from "./reducers/AuthReducer";
import axios from "axios";
import  UserState  from "./types";
import  useHistory  from "react-router-dom";
import  Plugins  from "@capacitor/core";
import  NavContext  from "@ionic/react";

// Initial State
const initialState: UserState = 
  user: ,
  error: null,
  loading: true,
  location: ,
  getLocation: () => ,
  UserLogin: () => ,
  UserRegister: () => ,
;

// Create Context
export const AuthContext = createContext<UserState>(initialState);

// Provider
export const AuthProvider: React.FC = ( children ) => 
  const URL = "https://backend.com/api/v1/auth";
  const [state, dispatch] = useReducer(AuthReducer, initialState);
  const [location, setLocation] = useState<object>( long: "", lat: "" );
  const [user, setUser] = useState();
  const  Toast, Geolocation  = Plugins;
  const  navigate  = useContext(NavContext);
  const history = useHistory();

  // Get Location
  const getLocation = async () => 
    try 
      const coordinates = await Geolocation.getCurrentPosition();
      const lat = coordinates.coords.latitude;
      const long = coordinates.coords.longitude;
      setLocation(
        long,
        lat,
      );
      console.log(location);
     catch (error) 
      console.log(error);
    
  ;

  getLocation();

  // Login
  const UserLogin = async (user: any) => 
    try 
      const res: any = await axios.post(`$URL/login`, user, 
        headers:  "Content-Type": "application/json" ,
      );
      dispatch(
        type: "LOGIN",
        user: res.data,
      );
      console.log(res.data);
      await Toast.show(
        text: "Login successfully",
        duration: "short",
        position: "bottom",
      );
      setUser(res.data);
      alert("Done");
      history.push("/dashboard/Home");
      // navigate("/dashboard/", "forward", "push");
     catch (error) 
      dispatch(
        type: "USER_ERROR",
        payload: error.message,
      );
      console.log(error.message);
      await Toast.show(
        text: `$error.message`,
        duration: "short",
        position: "bottom",
      );
    
  ;

  // Register
  const UserRegister = async (user: any) => 
    try 
      const res = await axios.post(`$URL/signup`, user, 
        headers:  "Content-Type": "application/json" ,
      );
      dispatch(
        type: "REGISTER",
        user: res.data,
      );
      console.log(res.data);
      await Toast.show(
        text: "Account created successfully",
        duration: "short",
        position: "bottom",
      );
      alert("Done");
      history.push("/login");
     catch (error) 
      dispatch(
        type: "USER_ERROR",
        payload: error.message,
      );
      console.log(error.message);
      await Toast.show(
        text: `$error.message`,
        duration: "short",
        position: "bottom",
      );
    
  ;

  return (
    <AuthContext.Provider
      value=
        user: state.user,
        loading: state.loading,
        error: state.error,
        location,
        getLocation,
        UserLogin,
        UserRegister,
      
    >
      children
    </AuthContext.Provider>
  );
;

我想我遗漏了一些东西...我想在登录和注册操作之后以编程方式导航到我的仪表板。即使我尝试使用 NavContext

【问题讨论】:

【参考方案1】:

您需要将组件包装在 withRouter() 中

export default withRouter(AuthProvider)

别忘了先导入:

import  useHistory, withRouter  from "react-router-dom";

【讨论】:

以上是关于使用react Context(Ionic-React)时未定义history.push()[重复]的主要内容,如果未能解决你的问题,请参考以下文章

(React Context 初学者)使用 react-router-dom 更改页面时,React Context 不启动

[react] 怎么使用Context开发组件?

[react] 为什么React并不推荐我们优先考虑使用Context?

react之context

react 使用context

使用 react-context 后出现黑屏问题