store.getState始终返回默认状态

时间:2020-05-17 16:18:55

标签: reactjs redux react-router-dom

我有一个带有Oauth的react应用,该应用通过快递和通行证在服务器上处理。我想配置基于身份验证的路由,即只有某些路由必须可供浏览而无需登录,否则导航到这些路由必须将用户重定向到“登录”页面。

因此,最初在应用程序加载(App.js)时,在componentDidMount方法中,我调用了一个API来提取用户。如果返回用户,则表示他已登录,否则已注销。我正在使用redux,因此在调用API后调度此操作后,此用户将存储在redux存储中。

我有一个auth.js文件,在其中检索用户状态,但是它始终为null,因此它返回false。为什么会这样?

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose} from 'redux';
import reducers from './reducers/index';
import thunk from 'redux-thunk';



const store = createStore(reducers, {}, compose(applyMiddleware(thunk),window.devToolsExtension && window.devToolsExtension() ));

export default store;

ReactDOM.render(<Provider store={store}><App/></Provider>, document.getElementById('root'));

App.js

import React from 'react';
import Login from './Login';
import Dashboard from './Dashboard';
import { BrowserRouter, Route} from 'react-router-dom';
import {connect} from 'react-redux';
import * as actions from '../actions/userActions';
import RouteAuthenticator from '../components/routes/routeAuthenticator';


class App extends React.Component {

    componentDidMount () {
        this.props.fetchUser();
    }

    render() {
        return (
            <div>
                <BrowserRouter>
                    <Route exact path="/" component={Login}/>
                    <RouteAuthenticator path="/home/dashboard" component={Dashboard}/>
                </BrowserRouter>
            </div>
        )
    }
}

export default connect(null, actions)(App);

RouteAuthenticator.js

import React from 'react';
import {Route, Redirect} from 'react-router-dom';
import isLoggedIn from '../../services/auth';

const RouteAuthenticator = ({ component: Component, ...rest }) => (
    <Route {...rest} render={(props) => (
      isLoggedIn()
        ? <Component {...props} />
        : <Redirect to='/' />
    )} />
)

export default RouteAuthenticator;

auth.js

import store from '../index';

export default function isUserLoggedIn () {
    const state = store.getState();
    if (state.user) {
        return true;
    }

    return false;
};

0 个答案:

没有答案