将自定义数据传递给React中的PrivateRoute组件 [英] Pass custom data to PrivateRoute component in React

查看:126
本文介绍了将自定义数据传递给React中的PrivateRoute组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是ReactJS的新手,并使用React开始我的第一个应用程序。我一直在观看视频并浏览各种教程,最后设法使用Login来构建我的第一个ReactRedux应用程序。

I am new in ReactJS and starting my first app with React. I've been watching videos and going through various tutorials and finally managed to scaffold my first ReactRedux app with Login.

我用 RehTraining网站的AuthWorkflow 示例。他们使用 PrivateRoute 组件来保护受保护的路由。我已经实现了它的工作。

I've used AuthWorkflow example of ReactTraining website. There they used a PrivateRoute component to secure protected routes. I've implemented it and its working.

问题:

现在我无法发送任何自定义数据或者喜欢用户数据到受保护的路线。我该如何发送?

Problem:
Now I can't send any custom data or like user data to protected route. How can I sent it?

代码

import React from "react";
import {
  BrowserRouter as Router,
  Route,
  Link,
  Redirect,
  withRouter
} from "react-router-dom";

////////////////////////////////////////////////////////////
// 1. Click the public page
// 2. Click the protected page
// 3. Log in
// 4. Click the back button, note the URL each time

const AuthExample = () => (
  <Router>
    <div>
      <AuthButton />
      <ul>
        <li>
          <Link to="/public">Public Page</Link>
        </li>
        <li>
          <Link to="/protected">Protected Page</Link>
        </li>
      </ul>
      <Route path="/public" component={Public} />
      <Route path="/login" component={Login} />

       // Here I want to pass the user data to protected component.
      <PrivateRoute path="/protected" component={Protected} user={username:'ariful', email:'test@example.com'}/>
    </div>
  </Router>
);

const fakeAuth = {
  isAuthenticated: false,
  authenticate(cb) {
    this.isAuthenticated = true;
    setTimeout(cb, 100); // fake async
  },
  signout(cb) {
    this.isAuthenticated = false;
    setTimeout(cb, 100);
  }
};

const AuthButton = withRouter(
  ({ history }) =>
    fakeAuth.isAuthenticated ? (
      <p>
        Welcome!{" "}
        <button
          onClick={() => {
            fakeAuth.signout(() => history.push("/"));
          }}
        >
          Sign out
        </button>
      </p>
    ) : (
      <p>You are not logged in.</p>
    )
);

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

const Public = () => <h3>Public</h3>;

// show the username here
const Protected = (props) => <h3>Protected Username: {props.user.username}</h3>;

class Login extends React.Component {
  state = {
    redirectToReferrer: false
  };

  login = () => {
    fakeAuth.authenticate(() => {
      this.setState({ redirectToReferrer: true });
    });
  };

  render() {
    const { from } = this.props.location.state || { from: { pathname: "/" } };
    const { redirectToReferrer } = this.state;

    if (redirectToReferrer) {
      return <Redirect to={from} />;
    }

    return (
      <div>
        <p>You must log in to view the page at {from.pathname}</p>
        <button onClick={this.login}>Log in</button>
      </div>
    );
  }
}

export default AuthExample;

如何成功将用户对象发送到受保护组件?

How can I successfully send the user object to protected component?

推荐答案

你需要传递传递给 ... rest 参数PrivateRoute 到组件上,但并非所有组件都需要对组件做出反应。您可以构建React路由器所需的其他参数

You need to pass on the ...rest params that you pass to PrivateRoute on to the component, however not all of them need to react the component. You can destructure other params that are needed by React router

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

这篇关于将自定义数据传递给React中的PrivateRoute组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆