Reactjs 路由器和PrivateOuter/history出现问题

Reactjs 路由器和PrivateOuter/history出现问题,reactjs,react-router,Reactjs,React Router,您好,我在重定向到在privaterouter上进行验证的页面时遇到问题 未处理的拒绝(TypeError):无法读取的属性“push” 未定义 在这一行: this.props.history.push(“/home”) 我的组成部分: import React, { Component } from 'react'; import api from '../services/api'; import { withRouter } from 'react-router'; class Lo

您好,我在重定向到在privaterouter上进行验证的页面时遇到问题

未处理的拒绝(TypeError):无法读取的属性“push” 未定义

在这一行:

this.props.history.push(“/home”)

我的组成部分:

import React, { Component } from 'react';
import api from '../services/api';
import { withRouter } from 'react-router'; 

class LoginForm extends Component {
    constructor(props){
        super(props);
        this.state = {
            login:'',
            password:'',
        };
        this.onSubmit = this.onSubmit.bind(this);
        this.onChange = this.onChange.bind(this);
    }
    async onSubmit(e){
        e.preventDefault();
        const {login, password } = this.state;

        const response = await api.post('/login', { login,password });
        const user = response.data.user.login;
        const {jwt} = response.data;

        localStorage.setItem('token', jwt);
        localStorage.setItem('user', user);
        this.props.history.push("/home");
    }
    onChange(e){
        this.setState({[e.target.name]: e.target.value});
    }

  render() {
    const { errors, login, password, isLoading } = this.state;
    return (
        <form onSubmit={this.onSubmit}>
            <label htmlFor="login">Login</label>
            <input type="text" name="login" id="login" value={login}  onChange={(e) => this.onChange(e)} placeholder="Informe seu login" />
            <label htmlFor="password">Senha</label>
            <input type="password" name="password" id="password" value={password} onChange={(e) => this.onChange(e)}   placeholder="Informe sua senha"/>
        <button className="btnEnt" type="submit">Entrar</button>
    </form>
    )
  }
}

export default withRouter (LoginForm);
import React,{Component}来自'React';
从“../services/api”导入api;
从“react router”导入{withRouter};
类LoginForm扩展组件{
建造师(道具){
超级(道具);
此.state={
登录名:“”,
密码:“”,
};
this.onSubmit=this.onSubmit.bind(this);
this.onChange=this.onChange.bind(this);
}
异步提交(e){
e、 预防默认值();
const{login,password}=this.state;
const response=wait api.post('/login',{login,password});
const user=response.data.user.login;
const{jwt}=response.data;
setItem('token',jwt);
setItem('user',user);
this.props.history.push(“/home”);
}
onChange(e){
this.setState({[e.target.name]:e.target.value});
}
render(){
const{errors,login,password,isLoading}=this.state;
返回(
登录
this.onChange(e)}占位符=“Informe seu login”/>
森哈
this.onChange(e)}占位符=“Informe sua senha”/>
诱捕者
)
}
}
使用路由器导出默认值(LoginForm);
我的路由器:

import React from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';

import Login from './pages/login/index';
import DashBoard from './pages/dashboard/index';
import PrivateRoute from './auth';

export default function Routes(){
    return(
        <BrowserRouter>
        <div>
            <Switch>
                <Route path="/" exact component = {Login}/> 
                <PrivateRoute path="/home" component = {DashBoard}/>              
            </Switch>
        </div>
        </BrowserRouter>
    );
}
从“React”导入React;
从“react router dom”导入{BrowserRouter,Switch,Route};
从“./pages/Login/index”导入登录名;
从“./pages/DashBoard/index”导入仪表板;
从“/auth”导入PrivateRoute;
导出默认函数路由(){
返回(
);
}
我的专用路由或身份验证路由器:

import React from 'react';

import { Route, Redirect} from 'react-router-dom';

const isAuth = () => {
    console.log('a');
    if(localStorage.getItem('token') !== null) {
        console.log('true')
        return true;
    }
    return false;
};

const PrivateRoute = ({component: Component, ...rest}) => {
    return (
        <Route
            {...rest}
            render={props => 
            isAuth() ? (
                <Component {...props} />
            ): (
                <Redirect
                to={{
                    pathname: '/',
                    state: {message: 'Usuário não autorizado'}
                }}
                />
            )}
        />
    );
}
export default PrivateRoute;
从“React”导入React;
从“react router dom”导入{Route,Redirect};
常量isAuth=()=>{
console.log('a');
if(localStorage.getItem('token')!==null){
console.log('true')
返回true;
}
返回false;
};
const privaterout=({component:component,…rest})=>{
返回(
isAuth()(
): (
)}
/>
);
}
导出默认私有路由;

我基本上有我的路由器,我也检查用户是否被允许进入这个页面,但我很难让它工作。

好吧,我读了你的代码,这是我的答案

您只需要从
react router dom
导入
withRouter
,而不需要从
react router
;)

像这样使用它

export default withRouter(LoginForm);

好吧,我读了你的代码,这是我的答案

您只需要从
react router dom
导入
withRouter
,而不需要从
react router
;)

像这样使用它

export default withRouter(LoginForm);

能否显示console.log(this.props)的结果?console.log(this.props)为空console.log(this.props.history)未定义是否确定?如果this.props为null,您不能接受this.props.history,因为您将获得“无法读取null的属性‘history’”错误。如果this.props为null,我不知道我哪里出错了。您可以将您的项目放到任何远程git存储库中,并给我访问权限吗?我将尽力帮助您显示console.log(this.props)的结果吗?console.log(this.props)为空console.log(this.props.history)未定义是否确定?如果this.props为null,您不能接受this.props.history,因为您将获得“无法读取null的属性‘history’”错误。如果this.props为null,我不知道我哪里出错了。您可以将您的项目放到任何远程git存储库中,并给我访问权限吗?我会尽力帮助你