当未经授权的用户访问reactjs

时间:2018-04-23 07:06:03

标签: reactjs react-redux

我正在使用PrivateRoute方法将未经授权的用户重定向到登录页面。这是该文件的代码。

我不想使用Dan Abramov的redux方法来处理Modal。

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

这是为此提到的路线

<Route path="/incidents" component={IncidentPage}/>
<Route path="/security-advisories" component={IncidentPage}/>
<Route path="/sign-in" component={SignIn}/>
<PrivateRoute path="/subscribe" component={Subscribe} isAuthenticated={this.props.isLoggedIn} />

但要求是在未经授权的用户点击私人路线时打开登录模式。

1 个答案:

答案 0 :(得分:0)

首次创建历史记录

import createHistory from 'history/createBrowserHistory'
const history = createHistory()
history.pushWithPrev = pathName => {
    history.push({
        pathname: pathName,
        state: { 
            from: history.location
        }
    })
}
export default history;

此功能将推送到保存先前位置的网址

在路由文件导入历史记录中

秒,并按如下所示使用它

import history from './history'
let switchLocation = history.location
    if(isAuthenticated) 
    {
        switchLocation = null
    } 
    else if(
            history.location && 
            history.location.state && 
            history.location.state.from
        ) {
        switchLocation = history.location.state.from
    }

<Router history={history}>
        <div>
             <Switch location={switchLocation}>
                   <Route path="/incidents" component={IncidentPage}/>
                   <Route path="/security-advisories" component={IncidentPage}/>
                   <Route path="/sign-in" component={SignIn}/>
             </Switch>
             <PrivateRoute path="/subscribe" component={Subscribe} isAuthenticated={this.props.isLoggedIn} />
        </div>
</Router>

并且每当需要保存以前的历史记录时,请使用历史记录的pushWithPrev函数

例如使用history.pushWithPrev('/subscribe')