无法从Reducer获取更新状态

时间:2018-12-02 14:23:20

标签: reactjs redux react-redux

我做了一个登录功能,将state中的reducerfalse更新为true。我在reducer和登录功能中进行了检查。但是,当我要检查另一个文件中的状态时,它会不断返回false

我的登录功能:

axios
    .post('api/user/login', {
        username: this.state.username,
        password: this.state.password
    })
    .then(response => {
        return response;
    })
    .then(json => {
        if (json.data.success) {
            store.dispatch(loginStatus(true));
            console.log('Login: ' + store.getState().loggedIn);
            window.location.assign('/');
        } else {
            alert('Login Failed!');
        }
    })
    .catch(error => {
        alert('An Error Occured!' + error);
        console.log(error);
    });

哪个返回true

我的减速器:

import { LOGIN_STATUS } from "../constants/action-types";

const initialState = {
    loggedIn: false
};

const rootReducer = (state = initialState, action) => {
    switch (action.type)  {
        case LOGIN_STATUS:
            state.loggedIn=action.payload;
            console.log('Reducer: ' + state.loggedIn);
            return {
                loggedIn: state.loggedIn=action.payload
            };
        default:
            return state;
    }
};

export default rootReducer;

还会返回true

但是在我的另一个文件中:

import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import  store from '../store/index';

const privateRouter = ({component: Component, ...rest }) => {

    const isLoggedIn = store.getState().loggedIn;
    console.log('PrivateRoute: ' + isLoggedIn);

    return (
        <Route
            {...rest}
            render={props =>
            isLoggedIn ? (
                <Component {...props} />
            ) : (
                <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
            )}
        />
    )
};

export default privateRouter;

它返回false。我在取得状态时做错了什么吗?因为在我的登录功能中,它确实返回更新后的状态。

更新

这是我的路由器:

   <Provider store={store}>
        <Router>
            <Switch>
                <Route path={'/login'} component={Login}/>
                <Route path={'/register'} component={Register}/>
                <PrivateRoute path={'/'} component={Home}/>
            </Switch>
        </Router>
    </Provider>

1 个答案:

答案 0 :(得分:2)

看来,一旦reducer改变状态,您的“ privateRouter”功能就不会触发。您需要触发privateRouter函数才能获取最新的存储。 不用导入存储,而是使用“提供程序”和“连接”将状态传递给组件。

https://www.sohamkamani.com/blog/2017/03/31/react-redux-connect-explained/