历史推送后react-router不会重新渲染

IT技术 reactjs react-redux
2021-05-12 12:53:33

我希望在用户登录后重新渲染/刷新,所以我正在使用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

在我的一个组件上。

在仪表板页面上刷新时,错误消失了,所以我正在寻找一种方法来重新呈现状态,并重定向到仪表板,这样用户就会存在,或者如果给出错误的凭据,则会引发未经授权的错误。

导航栏.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)

应用程序.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))
4个回答

所以看起来我没有使用导航栏history

所以而不是 this.props.history.push("/dashboard")

我用了 history.push('/dashboard')

登录.js

  .....
  componentDidMount() {
        // console.log(this.props.auth);
        if (this.props.auth.isAuthenticated) {
          history.push("/dashboard");
        }
      }
   componentDidUpdate(){
        if(this.props.auth.isAuthenticated){
            history.push("/dashboard")
        }
    }

导航栏.js

并改变这个

export const history = createBrowserHistory()

对此

export const history = createBrowserHistory({forceRefresh:true})

这是不使用withRouter()实例。

我仍然不得不history.pushauthActions.js loginUser函数中删除

我认为发生的事情是push您的Dashboard组件在setCurrentUser()操作有时间完成之前正在执行

dispatch(setCurrentUser(decoded))
history.push('/dashboard');

这两行代码正在运行到执行,而不是像它可能出现的那样同步(一个接一个)。

TypeError: Cannot read property 'user' of undefined

这可能来自您的Dashboard组件。您可能正在this.props.auth.user以某种身份使用类似的东西this.props.auth但尚未有效。

我们可以将您的代码配置为具有更同步的操作流。

您可能loginUser()Login组件中调用action-creator (有道理)。让我们确保我们带来withRouterreact-router-domauth-state从减速在最小。通过引入这两个,我们可以处理重定向componentDidUpdate()

因此,至少Login组件将使用以下导入和生命周期方法,如下所示:

import React from "react"
import { connect } from "react-redux"
import { loginUser } from "../../actions/authActions"
import { withRouter } from "react-router-dom"

class Login extends React.Component{
    componentDidMount(){
        if(this.props.auth.isAuthenticated){
            this.props.history.push("/dashboard")
        }
    }

    componentDidUpdate(){
        if(this.props.auth.isAuthenticated){
            this.props.history.push("/dashboard")
        }
    }

    onSubmit = (event) => {
        event.preventDefault()

        const userData = {
            email: this.state.email,
            password: this.state.password
        }

        this.props.loginUser(userData)
     }

    render(){
        return(
           ...yourmarkup
        )
    }
}

const mapStateToProps = (state) => {
    return{
        auth: state.auth
    }
}


const mapDispatchToProps = (dispatch) => {
    return{
        loginUser: (userData) => {
            dispatch(loginUser(userData))
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Login))

请注意,在您的authActions文件中,我们可以删除该history.push("/dashboard")行,因为我们正在从Login组件调用重定向

同步流程将是:

  1. 您在Login组件内提交登录表单,调用您的 loginUser()操作创建器。
  2. loginUser执行,它调度setCurrentUser,我们传入解码的用户。
  3. 您的减速器返回一个新状态,现在使用经过身份验证的用户。
  4. Login 组件从 redux-store 接收新的 props,导致组件重新渲染。
  5. componentDidUpdate()被触发后,我们验证 auth-state是否有经过身份验证的用户。如果为真,我们重定向到Dashboard组件。

您可以使用 withRouter hoc 然后使用 props.history -

import { withRouter } from 'react-router'

const Navbar = props => {
   return (
     <div onClick={() => props.history.push('your-path')}>
        Navigate to your-path
     </div>
   )
}

export default withRouter(Navbar)

如果您使用的是“React > 16.8.0”和功能组件,请尝试此操作。

import { useHistory } from "react-router-dom";

在您的功能组件中使用:

const history = useHistory();
history.push('/dashboard');