在呈现页面之前检查服务器中是否存在网址参数

时间:2018-10-30 16:27:40

标签: reactjs react-redux react-router

我正在创建一个应用程序,其中有一个URL参数,例如/competition/:id。当用户访问此URL时,我想在呈现之前检查比赛的ID是否确实存在。到目前为止,当我直接访问它时,它将呈现NavigationAdminNavigation,然后一秒钟后,它将重定向到/competition(因为我插入URL中的ID不存在)。我该怎么做才能获得更好的用户体验,因此它不显示页面,然后在几秒钟后重定向?

路由器

const AppRoute = ({ component, ...routeProps }) => {

  return (
      <Route {...routeProps} render={(props) => {
          return (
              <AppLayout { ...props} {...routeProps}>
                  {React.createElement(component, props)}
              </AppLayout>
          );
      }} />
  );
};

const AppLayout = (props) => {
  return (
          <div>
              {props.navBar ? React.createElement(props.navBar) : null}
              {props.adminNavBar ? React.createElement(props.adminNavBar) : null}
              {props.children}
          </div>
  );
};

class App extends Component {
  constructor(props) {
    super(props);



  }



  render() {
    return (
      <div className="app">
        <BrowserRouter >
          <Switch>


            <AppRoute exact path={routes.LANDING} component={() => <LandingPage />} navBar={Navigation}/>
            <AppRoute exact path={routes.DASHBOARD} component={() => <DashboardPage />}  navBar={Navigation} adminNavBar={AdminNavigation} />
            <AppRoute exact path={routes.LOGIN} component={() => <LoginPage />}/>
            <AppRoute exact path={routes.COMPETITIONS} component={() => <CompetitiondPage />}  navBar={Navigation} />
            <AppRoute exact path={`${routes.COMPETITIONS}/:id`} component={() => <CompetitiondPage />}  navBar={Navigation} adminNavBar={AdminNavigation} />


          </Switch>
        </BrowserRouter>
      </div>
    )
  }
}



export default withAuthentication(App);

竞争组件

class CompetitionPage extends Component {
    constructor(props) {
        super(props);

    }

    render() {
        const {
            authUser
        } = this.props;

        return (
            <div>
                </div>
        )
    }
};



const mapStateToProps = (state) => ({

});


const authCondition = (authUser) => !!authUser;

export default compose(
    withAuthorization(authCondition),
    withCompetition(),
    connect(mapStateToProps)
)(CompetitionPage);

具有竞争处理程序

const withCompetition = (condition) => (Component) => {
  class withCompetition extends React.Component {
    componentDidMount() {
      db.doGetUserCompetitionData(1).then(snapshot => {
        if(!snapshot.val()) {
          this.props.history.push(routes.COMPETITIONS);
        }
      }
      );

    }

    render() {
      return <Component {...this.props} />;
    }
  }

  const mapStateToProps = (state) => ({
    competitionData: state.CompetitionState.competitionData
  });

  return compose(
    withRouter,
    connect(mapStateToProps),
  )(withCompetition);
}

export default withCompetition;

0 个答案:

没有答案