【问题标题】:React router:I don't want user to directly navigate to pages by typing urls but allow going to pages only using links inside the app.React 路由器:我不希望用户通过输入 url 直接导航到页面,但只允许使用应用程序内的链接访问页面。
【发布时间】:2017-08-23 09:49:56
【问题描述】:

我的 Routes.js

<Route path="/game-center" component={GameCenter} />
      <Route path="/game-center/pickAndWin" component={PickAndWin} />
      <Route path="/game-center/memory" component={Memory} />
      <Route path="/game-center/summary" component={GameSummary} />
    </Route>
  </Router>

On Card Click 我将他引导至游戏或摘要,具体取决于游戏是实时的还是过期的。

cardClick=(type, name, status, gameId) => {
    console.log(`here${type}${status}`, name);
    this.props.dispatch(GameCenterActions.setShowGame());
    if (status === LIVE) {
      this.props.dispatch(GameCenterActions.selectGame({ type, name, status, gameId }));
      this.props.dispatch(GameCenterActions.resetShowSummary());
      hashHistory.push(LIVE_GAMES[type]);
    } else if (status === EXPIRED) {
      this.props.dispatch(GameCenterActions.setShowSummary());
      console.log(`${EXPIRED_GAMES}summary page here`);
      this.props.dispatch(GameCenterActions.selectGame({ type, name, status, gameId }));
      hashHistory.push('/game-center/summary');
    }
  }

当用户直接输入 url '/game-center/summary' 时,他不应该被允许并且应该被发送回主页。 这可能在反应路由器本身中吗?我想在我的整个应用程序中实现这一点。 我不希望用户通过输入 url 直接导航到页面,但只使用应用程序内的链接访问页面。

【问题讨论】:

    标签: javascript reactjs react-router url-routing


    【解决方案1】:

    您可以通过使用高阶组件来做到这一点。 比如你可以在用户通过身份验证时设置一个标志,然后将此 HOC 与 react router 中的指定组件附加

    import React,{Component} from 'react';
    import {connect} from 'react-redux';
    export default function(ComposedComponent){
      class Authentication extends Component{
        static contextTypes = {
          router : React.PropTypes.object
        }
        componentWillMount(){
          if(!this.props.user){
            this.context.router.push('/');
          }
        }
        componentWillUpdate(nextProps){
          if(!nextProps.user){
              this.context.router.push('/');
          }
        }
        render(){
          return(<ComposedComponent {...this.props}/>);
        }
      } 
    }
    

    然后在你的路线中

      <Route path="home" component={requireAuth(Home)}></Route>
    

    【讨论】:

    • 我不关心身份验证。 Game-center 组件有卡片,点击我可以转到“/sumary”或游戏本身。我不希望用户直接在 url 中输入“/game-center/summary”并转到摘要页面。
    • 您实际上可以自定义上面的代码,当用户尝试直接访问该页面时,他会被踢回主页。如this.context.router.push('/')
    • 我不确定我会在上面的代码中设置什么条件?我想确保他访问了游戏中心并单击了将路线更改为摘要的按钮。如果他直接输入了 url '/game-center/summary',他应该被重定向到家。能否请您详细说明。
    • 如果单击游戏中心,您可以简单地将flag 设置为true。稍后在HOC 中检查flag 是否为true,然后让用户通过其他把他踢回首页。
    • 嘿!我想我明白你在说什么。非常感谢你的帮助。 :)
    猜你喜欢
    • 1970-01-01
    • 2012-07-15
    • 2019-11-06
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多