首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React router:我不希望用户通过键入urls直接导航到页面,但只允许使用应用程序内部的链接转到页面。

React router:我不希望用户通过键入urls直接导航到页面,但只允许使用应用程序内部的链接转到页面。
EN

Stack Overflow用户
提问于 2017-08-23 17:49:57
回答 1查看 1K关注 0票数 1

我的Routes.js

代码语言:javascript
复制
<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>

在卡片点击上,我会根据游戏是有效的还是过期的,将他路由到游戏或摘要。

代码语言:javascript
复制
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‘时,他不应该被允许,而应该被送回主页。这在react路由器本身中是可能的吗?我想在我的整个应用程序中实现这一点。我不希望用户通过键入urls直接导航到页面,而是只使用应用程序内部的链接转到页面。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-23 17:54:29

您可以通过使用高阶组件来实现这一点。例如,您可以在用户通过身份验证时设置一个标志,然后将此HOC与react路由器中的指定组件相关联

代码语言:javascript
复制
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}/>);
    }
  } 
}

然后在你的路线中

代码语言:javascript
复制
  <Route path="home" component={requireAuth(Home)}></Route>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45836337

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档