【问题标题】:How to protect a react route based on an iframe如何保护基于 iframe 的反应路由
【发布时间】:2020-01-09 08:32:08
【问题描述】:

目前我有一个带有身份验证实现的反应路由器。它适用于简单的基于组件的路由。 这是我的 PrivateRoute 组件

import {  Route } from "react-router-dom";
import React from 'react';
import { Redirect } from 'react-router'

    export default function PrivateRoute ({component: Component, authed, ...rest}) {
        return (
          <Route
            {...rest}
            render={(props) => authed === true  
              ? <Component {...props} /> 
              : <Redirect to={{pathname: '/', state: {from: props.location}}} />} 
          /> 
        )
      }

这些类型的路由可以正常工作

<BrowserRouter>
        <Switch>
            <PrivateRoute authed={this.state.isAuthenticated} path='/register' component={RegisterPage} />
        </Switch>
    </BrowserRouter>

那些没有组件的路由会出现问题

<Route path="/route1" render={(props) => <iframe frameBorder={0} src={constans.urlRoute1} className="iframe" />} /> 

这是我提出的使其作为私有路由工作的解决方案,但问题是它缺少 url 重定向

<Route path="/route1" render={(props) => ((this.state.isAuthenticated) ? <iframe frameBorder={0} src={constans.urlRoute1} className="iframe" /> : <NewLandingPage {...props} /> )} />

那么如何使重定向与 iframe 一起工作?

【问题讨论】:

  • 什么意思?为什么不渲染&lt;Redirect to={'whereever'} /&gt; 而不是&lt;NewLandingPage {...props} /&gt;
  • 这实际上起到了作用 @SagiRika ,尽管我会尝试将它变成某种 protectediframeroute ,只是为了让它更干净
  • 我编辑了我的评论以包含编辑后的 ​​ProtectedRoute,它将匹配这两种情况。

标签: reactjs react-router


【解决方案1】:

将其作为答案发布,以防有​​人从 Google 偶然发现它:

<Route path="/route1" render={(props) => ((this.state.isAuthenticated) ? <iframe frameBorder={0} src={constans.urlRoute1} className="iframe" /> : <Redirect to='/my/link' /> )} />

我编辑了 ProtectedRoute,因此它也可以与 iframe 一起使用。

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

export default ({ component: Component, render: renderFn, authed, ...rest }) =>
  Component ? (
    <Route
      {...rest}
      render={props =>
        authed === true ? (
          <Component {...props} />
        ) : (
          <Redirect to={{ pathname: '/', state: { from: props.location } }} />
        )
      }
    />
  ) : (
    <Route {...rest} render={props => authed === true ? () => renderFn(props) : () => <Redirect to="my/link" />} />
  );

然后像这样调用 iFrame 路由:

<Route authed={this.state.isAuthenticated} path="/route1" render={props => <iframe frameBorder={0} src={constans.urlRoute1} className="iframe" />} />

【讨论】:

  • 能否请您告诉我您做了什么调整,以便我可以相应地编辑我的答案?
  • 我必须将 authed 状态传递给 iframe 路由的调用 &lt;PrivateRoute authed={this.state.isAuthenticated} path="/route1" render={props =&gt; &lt;iframe frameBorder={0} src={constans.route1} className="iframe" /&gt;} /&gt;
猜你喜欢
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
  • 2020-10-04
  • 2019-10-13
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 2018-01-28
相关资源
最近更新 更多