Я хочу перерисовать / обновить после того, как пользователь вошел в систему, поэтому я использую history.push
для этого.
import {history} from '../layout/Navbar'
export const loginUser = userData => dispatch => {
Axios.post('/users/login', userData)
.then( res => {
// retrieve token from the response
const token = res.data.token;
// console.log(token);
// pass the token in session
sessionStorage.setItem("jwtToken", token);
// set the auth token
setAuthToken(token);
// decode the auth token
const decoded = jwt_decode(token);
// pass the decoded token
dispatch(setCurrentUser(decoded))
history.push('/dashboard');
})
.catch(err => {
if(err.response.data){
console.log(err.response)
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
}
})
}
export const getUser = () => {
return (dispatch) => {
return Axios.get('/users/current_user',{
}).then( res => {
const data = res.data
dispatch({type: GET_CURRENT_USER, data})
})
}
}
export const setCurrentUser = (decoded, dispatch) => {
return{
type:SET_CURRENT_USER,
payload:decoded,
}
}
Вместо этого он, похоже, не рендерится заново, потому что я получаю ошибку, которая должна иметь ошибку только в том случае, если пользователь не вошел в систему.
Например
TypeError: Cannot read property 'user' of undefined
на одном из моих компонентов.
При обновлении на странице панели мониторинга ошибка исчезает, поэтому я ищу способ повторного отображения состояния и перенаправления на панель мониторинга таким образом, чтобы пользователь существовал или выдавал несанкционированную ошибку, если ему были присвоены неверные учетные данные.
Navbar.js
import React, {Component} from "react";
import {BrowserRouter, Link, Route, Switch} from "react-router-dom";
import PrivateRoute from '../components/PrivateRoute';
import Home from '../components/Home';
import Dashboard from '../components/Dashboard';
import {connect} from 'react-redux';
import Login from '../components/Login';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import {logoutUser} from '../actions/authActions';
import SignUp from "../components/SignUp";
import Grid from '@material-ui/core/Grid';
import {createBrowserHistory} from 'history';
// import createBrowserHistory from 'history/createBrowserHistory'
export const history = createBrowserHistory()
class Navbar extends Component {
logout = (e) => {
e.preventDefault();
this.props.logoutUser();
}
render() {
// LINKS
const authLinks = (
<span>
<Button>
<Link to="/dashboard" color="primary">
Dashboard
</Link>
</Button>
<Button onClick={this.logout} to="/">
<span>Logout</span>
</Button>
</span>
);
const guestLinks = (
<span>
<Button>
<Link to="/login">
Login
</Link>
</Button>
<Button>
<Link to="/signup">
Sign Up
</Link>
</Button>
</span>
);
return (
<div>
<BrowserRouter history={history}>
<AppBar position="static">
<Toolbar>
<Grid justify="space-between" container >
<Typography variant="h6" style={{ color: '#fff'}}>
Image Upload App
</Typography>
{/* if is authenticated, will render authlinks
if not will render guest links
*/}
<Grid item>
<Button align="right">
<Link style={{ color:'#fff'}} underline="none" to="/">
Home
</Link>
</Button>
{this.props.auth.isAuthenticated ? authLinks : guestLinks}
</Grid>
</Grid>
</Toolbar>
</AppBar>
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/signUp" component ={SignUp}/>
<Route exact path="/login" component={Login}/> {/* private routes for users who are authenticated */}
<PrivateRoute exact path="/dashboard" component={Dashboard}></PrivateRoute>
</Switch>
</BrowserRouter>
</div>
)
}
}
const mapDispatchToProps = (dispatch) => ({
logoutUser: () => dispatch(logoutUser())
})
const mapStateToProps = (state) => ({
auth: state.auth
})
export default connect(mapStateToProps,mapDispatchToProps)(Navbar)
App.js
import React, { Component } from 'react';
import './App.css';
import setAuthToken from "./actions/utils/setAuthToken";
import Navbar from './layout/Navbar';
import jwt_decode from "jwt-decode";
import store from './store';
import {setCurrentUser, logoutUser, getUser } from './actions/authActions';
import { Provider } from "react-redux";
// JWT TOKEN
if (sessionStorage.jwtToken) {
// Set auth token header auth
setAuthToken(sessionStorage.jwtToken);
// Decode token and get user info and exp
const decoded = jwt_decode(sessionStorage.jwtToken);
// Set user and isAuthenticated
store.dispatch(setCurrentUser(decoded));
store.dispatch( getUser());
// Check for expired token
const currentTime = Date.now() / 1000;
if (decoded.exp < currentTime) {
// Logout user
store.dispatch(logoutUser());
// Redirect to login
window.location.href = "/login";
}
}
class App extends Component {
render(){
return (
<Provider store={store}>
<Navbar/>
</Provider>
);
}
}
export default App;
Логин
import React, { Component } from "react";
import {connect} from 'react-redux';
import {Redirect} from "react-router-dom";
import {loginUser, googleLogin } from '../actions/authActions';
import Grid from '@material-ui/core/Grid';
import PropTypes from "prop-types";
import { GoogleLogin } from "react-google-login";
import Divider from '@material-ui/core/Divider';
import Typography from '@material-ui/core/Typography';
import { GoogleLoginButton} from "react-social-login-buttons";
import LoginForm from './LoginForm/LoginForm';
import {history} from '../layout/Navbar';
import { withRouter } from "react-router-dom";
// const onSuccess = response => console.log(response);
// const onFailure = response => console.error(response);
class Login extends Component{
constructor() {
super();
this.state = {
formData:{
username:'',
password:'',
isAuthenticated: false,
},
errors:{}
}
}
logInGithub = (e) => {
e.preventDefault();
console.log('hello');
this.props.githubLogin();
}
componentDidMount() {
// console.log(this.props.auth);
if (this.props.auth.isAuthenticated) {
this.props.history.push("/dashboard");
}
}
componentDidUpdate(){
if(this.props.auth.isAuthenticated){
this.props.history.push("/dashboard")
}
}
handleChange = (e) => {
e.preventDefault();
const {formData} = this.state;
this.setState({
formData: {
...formData,
[e.target.name]: e.target.value
}
});
}
handleSubmit = (e) => {
e.preventDefault();
const {formData} = this.state;
const {username, password} = formData;
const creds = {
username,
password
}
this.props.loginUser(creds, this.props.history);
// console.log(creds);
}
render(){
const googleLogin = response => {
let googleData;
googleData = {
googleID: response.profileObj.googleId,
email: response.profileObj.email,
// password: "",
};
console.log(googleData);
this.props.googleLogin(googleData);
};
return(
<div>
<Grid container justify="center" spacing={0}>
<Grid item sm={10} md={6} lg={4} style={{ margin:'20px 0px'}}>
<Typography variant="h4" style={{ letterSpacing: '2px'}} >
Sign In
</Typography>
{this.props.auth.errors ? (
this.props.auth.errors.map( (err, i) => (
<div key={i} style={{color: 'red' }}>
{err}
</div>
))
):(
null
)}
<LoginForm
mySubmit={this.handleSubmit}
myChange={this.handleChange}
username={this.state.username}
password={this.state.password}
/>
<Grid item sm={12}>
<Typography align="center" variant="h4" style={{ letterSpacing: '6px'}} >
OR
</Typography>
<Divider style={{ width: '200px', margin:'20px auto', backgroundColor:'#000000'}} variant="middle" />
</Grid>
</Grid>
</Grid>
</div>
)
}
}
Login.propTypes = {
loginUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
errors: PropTypes.object
};
const mapStateToProps = (state) => ({
auth: state.auth
})
const mapDispatchToProps = (dispatch) => ({
loginUser: (userData) => dispatch(loginUser(userData)),
googleLogin: (userData) => dispatch(googleLogin(userData))
})
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Login))