功能组件内部的props.history.push不呈现该组件

时间:2019-12-01 06:39:07

标签: reactjs react-router react-context

我正在使用上下文API,并且在我的AuthContextProvider内部,我有一个函数,我先调用该函数然后更改路由;问题是它更改了路由但没有呈现组件,我也不知道为什么。我相信,如果我将auth-context.js类转换为基于类的类,它将起作用。

我尝试返回Redirect to ="/ />,但这不起作用。  我很沮丧。我希望有人能帮忙

auth-context.js
import React, { useState } from 'react';
import { withRouter, Redirect } from 'react-router-dom';
import axios from 'axios';
export const AuthContext = React.createContext({
  isAuth: false,
  login: () => {},
  seedFirebase: () => {}
});

const AuthContextProvider = props => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  console.log(props);
  const loginHandler = () => {
    setIsAuthenticated(true);
    props.history.push('/'); //this changes the route but does not render the component
  };
  //THIS FUNCTION SEEDS THE FIREBASE DATABASE
  const seedDb = () => {
    const data = {
      items: 'Folders'
    };
    // axios.post('/items.json', data).then(resp => console.log(resp.data));
  };
  return (
    <AuthContext.Provider
      value={{
        login: loginHandler,
        isAuth: isAuthenticated,
        seedFirebase: seedDb
      }}
    >
      {props.children}
    </AuthContext.Provider>
  );
};
export default withRouter(AuthContextProvider);

2 个答案:

答案 0 :(得分:0)

一个简单的解决方案是在源目录的helper文件夹中创建一个history.js文件。 将以下代码添加到history.js文件中。

p A
p B
p C

然后将history.js文件导入到您需要的以下文件中。

import { createBrowserHistory } from 'history';
export default createBrowserHistory();

然后使用import history from '/helpers/history'; 重定向到home组件。

希望这会有所帮助!

答案 1 :(得分:0)

发布此信息,以防其他人遇到此特殊问题。我使用以下逻辑解决了这个问题:我检入了调用登录功能的组件,如果Heterotype为true,我将重定向到主页。

相关问题