React Redux不维持状态

时间:2019-02-18 15:14:18

标签: reactjs redux

我有一个简单的redux状态,如果用户登录它将显示Posts,注销,Dashboard和New Post。如果不。渲染首页,登录和登录。

我不认为本地存储是我要寻找的

How do I maintain react-redux state?

当前,如果用户登录,则导航栏会更新,但刷新后会恢复为“首页”,“登录”和“登录”。

用户缩减工具

import { SET_USER, POST_AUTH, GET_USER, SIGN_GITHUB,  REG_SUC, REG_FAIL, LOG_FAIL} from '../actions/';


const initialState = {
    authError: null,
    isAuthenticated:false,
    token: null,
    user: [],
    redirectPath: null

}

export default (state = initialState, action) => {
    switch (action.type) {
        case SET_USER:
        console.log(action.payload);
            return ({
                ...state,
                user:action.user,
                token: action.payload,
                isAuthenticated:true,
            });
        case LOG_FAIL:
            return({
                ...state,
                authError:action.err.response.data
            });
        case GET_USER:
            return({
                ...state,

            });
        case SIGN_GITHUB:
            return({
                ...state,
                token:action.payload,
                isAuthenticated:true
            })
        case REG_SUC:
            return({
                ...state,
                user:action.user,
                token: action.payload
            });
        case REG_FAIL:
            return({
                ...state,
                authError:action.err.response.data
            });


        default:
            return state
    }
}

redux操作

export const logIn =  (user) => { 
    return (dispatch) => {
        axios.post(process.env.REACT_APP_BASE_SIGN_IN,{
            username: user.username,
            password: user.password,

        }).then( (res) => {
            const token = res.data.token;
            localStorage.setItem('auth', token);
            setAuthToken(token);
            // history.push('/dashboard');
            dispatch({type: SET_USER, user});
        }).catch((err)=> {

            dispatch({type:  LOG_FAIL, err});
            console.log(err.response.data); // not even showing err console.
        })

    }
}

导航栏

import React from 'react';
import {BrowserRouter as Router, Route, Link} from "react-router-dom";
import signUp from '../auth/signUp';
import signIn from '../auth/signIn';
import Post from '../Post';
import Forgot from '../account/Forgot';
import Home from '../Home';
import Posts from '../Posts';
import Users from '../account/Users';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import Button from '@material-ui/core/Button';
import {withStyles} from '@material-ui/core';
import Dashboard from '../account/dashBoard';
import {connect} from 'react-redux';
import {createBrowserHistory} from 'history';
import PropTypes from 'prop-types';
import {compose} from 'redux';
import axios from 'axios';
import updatePassword from '../account/updatePassword';
import ResetPassword from '../account/ResetPassword';

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

const styles = {
    // This group of buttons will be aligned to the right

    rightToolbar: {
        color: '#fff',
        textDecoration: 'none',
        a: {
            color: '#fff'

        }
    },
    rightt: {
        marginLeft: 'auto',
        marginRight: 24
    },
    root: {
        flexGrow: 1
    },
    menuButton: {
        marginRight: 16,
        marginLeft: -12
    }
};

const logout = () => {
    // e.preventDefault();
    axios.get(process.env.REACT_APP_BASE_URL + '/api/users/logout');
    localStorage.removeItem('auth');
    history.push('/');

};

const Navbar = ({classes, isAuthenticated}) => (

    <Router history={history}>

        <div className={classes.root}>

            <AppBar position="static" className={classes.navbar}>
                <Toolbar>
                    <IconButton color="inherit" aria-label="Menu">
                        <MenuIcon/>
                    </IconButton>
                    <Typography variant="h6" color="inherit">
                        Express Seqeuelize App
                    </Typography>
                    <Typography classcolor="inherit" className={classes.rightt}>


                    {!isAuthenticated && (

                    <Button>
                        <Link to="/" className={classes.rightToolbar}>
                            Home
                        </Link>
                    </Button>

                    )}
                        {isAuthenticated && (
                            <Button>
                                <Link className={classes.rightToolbar} to="/posts">
                                    Posts
                                </Link>
                            </Button>

                        )}

                        {!isAuthenticated && (

                            <Button>
                                <Link to="/signUp" className={classes.rightToolbar}>
                                    Sign Up
                                </Link>
                            </Button>

                        )}

                        {!isAuthenticated && (

                            <Button>
                                <Link to="/signIn" className={classes.rightToolbar}>
                                    Sign In
                                </Link>
                            </Button>

                        )}

                        {isAuthenticated && (
                            <Button>
                                <Link className={classes.rightToolbar} to="/Post">
                                    New Post
                                </Link>
                            </Button>

                        )}


                        {isAuthenticated && (
                            <Button>
                                <Link to="/dashboard" className={classes.rightToolbar}>
                                    Dashboard
                                </Link>
                            </Button>

                        )}

                            {isAuthenticated && (
                            <Button onClick={logout}>
                                <Link className={classes.rightToolbar} to={'/logout'}>
                                    LogOut
                                </Link>
                            </Button>
                          )}


                    </Typography>

                </Toolbar>
            </AppBar>


            <Route exact path="/signUp" component={signUp}/>
            <Route exact path="/" component={Home}/>
            <Route exact path="/signIn" component={signIn}/>
            <Route exact path="/Post" component={Post}/>
            <Route exact path="/Posts" component={Posts}/>
            <Route path="/Forgot" component={Forgot}/>
            <Route path="/users" component={Users}/>
            <Route exact path="/dashboard" component={Dashboard}/>
            <Route exact path="/logout"/>
            <Route exact path="http://127.0.0.1:8000/api/users/auth/github"/>
            <Route path="/test"/>
            <Route path="/reset/:token" component={ResetPassword}/>
            <Route exact path="/updatePassword/:username" component={updatePassword}/>
        </div>
    </Router>

);

const mapStateToProps = (state) => ({
    token: state.user.getToken,
    isAuthenticated: state.user.isAuthenticated
})

const mapDispatchToProps = (dispatch) => ({
    //   logIn: (user) => dispatch(logIn(user))

});

Navbar.propTypes = {
    isAuthenticatd: PropTypes.string

}

// export default withStyles(styles)(Navbar);
export default compose(connect(mapStateToProps, mapDispatchToProps), withStyles(styles))(Navbar);

2 个答案:

答案 0 :(得分:1)

刷新后Redux不会保存数据,将redux容器视为一个简单的对象,尝试使用localStorage来设置令牌,只需简单地说:

localStorage.setItem('token',token);

并通过以下方式访问它:

localStorage.getItem('token);

答案 1 :(得分:0)

Redux不会保持页面加载之间的状态,就像javascript在重新加载时不记得任何变量值一样。 页面重新加载后,它将丢失所有状态,并将被重新实例化。

您可以尝试将令牌保存在cookie中,并在安装应用程序时检查令牌是否存在。 (不要忘记在注销时删除cookie)。您也可以将令牌保存在本地存储中,但是我认为这不是一个好习惯。