我不知道我要去哪里错 通过单击输入按钮,我验证了我的用户并使用this.props.history.push(“ / home”); 而且不起作用
我的登录名。 js
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 LoginForm;
我的路由器。 js:
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(){
console.log('a')
return(
<BrowserRouter>
<Switch>
<PrivateRoute path="/home" component = {DashBoard}/>
</Switch>
</BrowserRouter>
);
} <PrivateRoute path="/home" component = {DashBoard}/>
</Switch>
</BrowserRouter>
);
}
我的身份验证。 js:
import { Route, Redirect} from 'react-router-dom';
const isAuth = () => {
console.log('a');
if(localStorage.getItem('token') !== null) {
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,{组件}; 从“ ../../components/Home”导入主页;
class DashBoard extends Component {
render() {
return (
<Home />
)
}
}
export default DashBoard;
错误:
未处理的拒绝(TypeError):无法读取的属性“推” 未定义 未捕获(承诺)TypeError:无法读取的属性“ push” 未定义我真的不知道我能做错的是没有重定向, 我已经尝试了所有可能的替代方法。
答案 0 :(得分:0)
在您可以在React组件中使用历史记录之前,需要将其包装在withRouter中。
答案 1 :(得分:0)
import history from 'add your path'
export default function Routes() {
console.log('a')
return (
<BrowserRouter history={history}>
<Switch>
<PrivateRoute exact path="/home" component={DashBoard} />
</Switch>
</BrowserRouter>
)
}
更改路由器文件
import { withRouter } from 'react-router-dom';
export default withRouter(LoginForm);
在此组件中添加withRouter