React-PrivateRoute和索引文件中的功能组件

时间:2019-05-02 13:45:58

标签: reactjs react-redux react-router

我正在将React Router和Redux用于一个简单的React应用程序(带有MaterialUI)。 我想使我的应用程序具有大部分功能组件,并且在某些情况下尝试处理它有一些困难:

1-私有路由无状态- 我正在使用Firebase,并且要检测用户是否登录,我将一些信息存储在redux存储中。作为React Router教程,我使用这些信息进行专用和公用路由。但是这些组件当前不起作用,我不知道如何继续使它们起作用。有什么建议吗?

index.js

import React from "react";
import { render } from "react-dom";

import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import logger from "redux-logger";
import { IntlProvider } from "react-intl";
import { locale, messages } from "./i18n/i18n";
import { BrowserRouter as Router, Switch } from "react-router-dom";
import PublicRoute from "./components/PublicRoute";
import PrivateRoute from "./components/PrivateRoute";

import rootReducer from "./reducers/root.reducer";
import firebase from "./firebase";

import AppBar from "./components/AppBar/AppBar";
import Drawer from "./components/Drawer/Drawer";
import Login from "./containers/Login/Login";
import ForgotPassword from "./containers/ForgotPassword/ForgotPassword";
import Dashboard from "./containers/Dashboard/Dashboard";

const store = createStore(rootReducer, applyMiddleware(thunk, logger));

render(
  <Provider store={store}>
    <IntlProvider locale={locale} messages={messages}>
      <Router>
        <div>
          <AppBar />
          <Drawer />
          <Switch>
            <PublicRoute exact path="/" component={Login} />
            <PublicRoute path="/forgotpassword" component={ForgotPassword} />
            <PrivateRoute path="/dashboard" component={Dashboard} />
          </Switch>
        </div>
      </Router>
    </IntlProvider>
  </Provider>,
  document.getElementById("root")
);

PrivateRoute.js

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

const PrivateRoute = ({ component: Component, user, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      user ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/",
            state: { from: props.location }
          }}
        />
      )
    }
  />
);

const mapStateToProps = (state, props) => ({
  user: state.auth.user
});

export default connect(mapStateToProps)(PrivateRoute);

2-AppBar /抽屉无状态

我的appbar /抽屉有相同的问题。 它们当前在上面的代码中发布的索引中。 仅当用户连接并且我需要通过redux存储传递连接状态时,它们才应显示。

我猜这两个问题都有相同的解决方案,但我找不到。 有人给我一个吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

路线(PrivateRoute)需要一个路径参数,如下所示:

const PrivateRoute = ({ component: Component, path,user, ...rest }) => (

<Route
    path={path}
    {...rest}
    render={props =>
      user ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/",
            state: { from: props.location }
          }}
        />
      )
    }
  />
)