简体   繁体   English

如何使用React Router 4配置专用路由

[英]How to configure private routes with react router 4

I have the following code for private route component. 我有以下用于私有路由组件的代码。

import React from 'react';
import {Route, Redirect} from 'react-router-dom';
import {connect} from 'react-redux';

class PrivaetRoute extends React.Component {

    render() {
        const {component: Component, ...rest} = this.props;

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

function mapStateToProps(state) {
    return {
        loggedIn: state.loggedIn
    }
}

export default connect(mapStateToProps)(PrivaetRoute);

and I have the following code for the app component that renders different routes 我为呈现不同路线的应用程序组件提供了以下代码

import React from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import Reboot from 'material-ui/Reboot';

/**
 * Local
 * */

import IndexPage from '../pages/Index';
import DashboardPage from '../pages/Dashboard';
import PrivateRoute from '../containers/PrivateRoutes';

export default class App extends React.Component {

    render() {
        return (
            <div>
                <BrowserRouter>
                    <div>
                        <Reboot/>
                        <Switch>
                            <Route exact path="/" component={IndexPage}/>
                            <PrivateRoute path="/dashboard" component={DashboardPage}/>
                        </Switch>
                    </div>
                </BrowserRouter>
            </div>
        );
    }
}

How I have designed login system is that my redux action alters the loggedIn state to be true when authentication is complete. 我设计登录系统的方式是,当身份验证完成时,我的redux操作会将loginIn状态更改为true。 I have checked using chrome developer tool that loggedIn state is indeed being set to loggedIn:true ; 我已经使用chrome开发人员工具检查过, loggedIn状态确实设置为loggedIn:true however, when I change the url to /dashboard all the states refreshes (even the redux states) and I get redirected to / . 但是,当我将url更改为/dashboard所有状态都会刷新(甚至是redux状态),然后重定向到/ What am I doing wrong? 我究竟做错了什么?

** edit redux container **编辑redux容器

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware} from 'redux';
import reduxThunk from 'redux-thunk';
import {composeWithDevTools} from 'redux-devtools-extension';

import App from './components/App';
import reducers from './reducers';

const store = createStore(reducers, {}, composeWithDevTools(applyMiddleware(reduxThunk)));

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

You should use Redux 您应该使用Redux

You can read about it here . 你可以在这里阅读。

Why you should use Redux? 为什么要使用Redux?

Because Redux serves as a global state container, it means no matter which page you go, the state will not be reset. 因为Redux用作全局状态容器,所以这意味着无论您进入哪个页面,状态都不会被重置。

How to use Redux with React-Router correctly? 如何在React-Router中正确使用Redux?

Just remember one thing, Redux should be the parent of React-Router. 只需记住一件事,Redux应该是React-Router的父级。
So it should look something like this 所以应该看起来像这样

<Provider>
    <Router>
        <YourApp/>
    </Router>
</Provider>

FYI: Provider is the state container of Redux. 仅供参考: Provider是Redux的状态容器。

If you make <Router> as the parent of <Provider> , you'll be facing the same problem again. 如果将<Router>作为<Provider>的父级,则将再次面临相同的问题。

Hope it helps. 希望能帮助到你。

It wasn't at all to do with the route settings. 这与路由设置完全无关。

I was using combineReducers function and I did not realize that it wraps all the states into a parent object so I had to access its key before accessing the actual object that I wanted to access. 我使用的是combineReducers函数,但我没有意识到它会将所有状态都包装到一个父对象中,因此我必须在访问要访问的实际对象之前访问其键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM