Reactjs props.history.push内部功能组件';不要渲染组件

Reactjs props.history.push内部功能组件';不要渲染组件,reactjs,react-router,react-context,Reactjs,React Router,React Context,我使用的是上下文API,在AuthContextProvider中,我调用了一个函数,然后更改了路由;问题是它改变了路径,但没有渲染组件,我不知道为什么。我相信,如果我将auth-context.js类转换为基于类的类,它就会工作 我尝试返回重定向到=“//>,但这不起作用。 我被难住了。如果有人能帮忙,我会很高兴的 auth-context.js import React, { useState } from 'react'; import { withRouter, Redirect } f

我使用的是上下文API,在AuthContextProvider中,我调用了一个函数,然后更改了路由;问题是它改变了路径,但没有渲染组件,我不知道为什么。我相信,如果我将auth-context.js类转换为基于类的类,它就会工作

我尝试返回
重定向到=“//>
,但这不起作用。 我被难住了。如果有人能帮忙,我会很高兴的

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);
auth-context.js
从“React”导入React,{useState};
从“react router dom”导入{withRouter,Redirect};
从“axios”导入axios;
export const AuthContext=React.createContext({
伊萨思:错,
登录:()=>{},
seedFirebase:()=>{}
});
const AuthContextProvider=props=>{
const[isAuthenticated,setIsAuthenticated]=useState(false);
控制台日志(道具);
const loginHandler=()=>{
setIsAuthenticated(真);
props.history.push(“/”);//这会更改路由,但不会呈现组件
};
//此函数用于为FIREBASE数据库种子
const seedDb=()=>{
常数数据={
项目:“文件夹”
};
//post('/items.json',data.),然后(resp=>console.log(resp.data));
};
返回(
{props.children}
);
};
使用路由器导出默认值(AuthContextProvider);

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

import { createBrowserHistory } from 'history';
export default createBrowserHistory();
然后将history.js文件导入到所需的以下文件中

import history from '/helpers/history';
然后使用
history.push('/')
重定向到主组件


希望这有帮助!

如果其他人有此特殊问题,请发布此消息。我使用以下逻辑解决了此问题:我签入调用登录功能的组件,如果
已验证,我将重定向到主页。

您好,感谢您的回复,不幸的是,这仍然是同一个问题-它更改了路由,但组件从未被渲染。您是否像这样在App.js中添加了路由?