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

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

问题描述

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

我使用了 ReactTraining 网站的 AuthWorkflow 示例.在那里,他们使用了一个 PrivateRoute 组件来保护受保护的路由.我已经实现了它并且它正在运行.

问题:
现在我无法将任何自定义数据或像用户数据发送到受保护的路由.如何发送?

代码

从react"导入React;进口 {BrowserRouter 作为路由器,路线,关联,重定向,带路由器来自反应路由器-dom";//////////////////////////////////////////////////////////////1.点击公共页面//2. 点击受保护的页面//3. 登录//4.点击后退按钮,每次记下urlconst AuthExample = () =>(<路由器><div><AuthButton/><ul><li><Link to="/public">公共页面</Link><li><Link to="/protected">受保护页面</Link><Route path="/public" component={Public}/><Route path="/login" component={Login}/>//这里我想将用户数据传递给受保护的组件.<PrivateRoute path="/protected" component={Protected} user={username:'ariful', email:'test@example.com'}/>

</路由器>);const fakeAuth = {isAuthenticated: 假,认证(CB){this.isAuthenticated = true;设置超时(CB,100);//假异步},退出(CB){this.isAuthenticated = false;设置超时(CB,100);}};const AuthButton = withRouter(({历史}) =>fakeAuth.isAuthenticated ?(<p>欢迎!{" "}<按钮onClick={() =>{fakeAuth.signout(() => history.push("/"));}}>登出</p>) : (<p>您尚未登录.</p>));const PrivateRoute = ({ component: Component, ...rest }) =>(<路线{...休息}渲染={道具=>fakeAuth.isAuthenticated ?(<组件{...道具}/>) : (<重定向到={{路径名:/登录",状态:{来自:props.location}}}/>)}/>);const 公共 = () =><h3>公共</h3>;//这里显示用户名const Protected = (props) =><h3>受保护的用户名:{props.user.username}</h3>;class Login 扩展了 React.Component {状态 = {重定向到引用:假};登录 = () =>{fakeAuth.authenticate(() => {this.setState({ redirectToReferrer: true });});};使成为() {const { from } = this.props.location.state ||{来自:{路径名:/"}};const { redirectToReferrer } = this.state;如果(重定向到Referrer){return <Redirect to={from}/>;}返回 (<div><p>您必须登录才能查看位于 {from.pathname} 的页面</p><button onClick={this.login}>登录</button>

);}}导出默认的 AuthExample;

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

解决方案

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

const PrivateRoute = ({ component: Component, exact, strict, path, ...rest }) =>(<路线精确={精确}严格={严格}路径={路径}渲染={道具=>fakeAuth.isAuthenticated ?(<组件 {...props} {...rest}/>) : (<重定向到={{路径名:/登录",状态:{来自:props.location}}}/>)}/>);

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.

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?

Code

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?

解决方案

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天全站免登陆