Reactjs 在盖茨比中以编程方式限制路由

Reactjs 在盖茨比中以编程方式限制路由,reactjs,react-router,gatsby,Reactjs,React Router,Gatsby,在盖茨比中,我如何以编程方式限制路线?通过使用,我发现可以使用执行,但在盖茨比中如何实现这一点?做这样的事 <Route exact path="/" render={() => ( loggedIn ? ( <Redirect to="/dashboard"/> ) : ( <PublicHomePage/> ) )}/> async handleSubmit(event) { event.preventDefault

在盖茨比中,我如何以编程方式限制路线?通过使用,我发现可以使用
执行
,但在盖茨比中如何实现这一点?做这样的事

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/dashboard"/>
  ) : (
    <PublicHomePage/>
  )
)}/>
async handleSubmit(event) {
  event.preventDefault()
  await handleLogin(this.state)
    .then(response => _this.setState({isLoggedIn: isLoggedIn()}))
    .catch(err => { console.log(err) });
}
此外,我还可以将
与此一起使用

不幸的是,当我使用

render() {
  if (isLoggedIn()) {
    return <Redirect to={{ pathname: `/app/profile` }} />
  }

  return (
    <View title="Log In">
      <Form
        handleUpdate={e => this.handleUpdate(e)}
        handleSubmit={e => this.handleSubmit(e)}
      />
    </View>
  )
}
render(){
if(isLoggedIn()){
返回
}
返回(
此.handleUpdate(e)}
handleSubmit={e=>this.handleSubmit(e)}
/>
)
}
…虽然我确实执行了
,但我注意到,在重定向之前的一瞬间,表单字段被清空,只有在这之后,我才被重定向到
/app/profile
(从
/app/login
)。此外,如果我输入了错误的密码,我的整个表单都将重新呈现(再次重新呈现
)。这将是一个糟糕的用户体验,因为他们必须从头开始重新输入所有信息,加上我无法为无效输入添加样式,等等。我想知道是否有更好的方法与盖茨比一起实现这一点


或者,我是否需要从头开始构建表单功能(即更直接地使用Redux、Router等),而不是依赖于盖茨比更高的抽象级别?

盖茨比在引擎盖下使用react Router,因此,您可以使用它定义仅客户端的路由

与盖茨比一样,github回购协议中有一个非常好的例子:

关于它的文档:

总而言之,这就是我们所做的:

1) 在/src/components
const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      !isLoggedIn() ? (
        // If we’re not logged in, redirect to the login page.
        <Redirect to={{ pathname: `/app/login` }} />
      ) : (
        <Component {...props} />
      )
    }
  />
);
const App = () => (
  <div>
    <PrivateRoute path="/app/profile" component={Home} />
    <PrivateRoute path="/app/details" component={Details} />
    <Route path="/app/login" component={Login} />
  </div>
);
exports.onCreatePage = async ({ page, boundActionCreators }) => {
  const { createPage } = boundActionCreators

  // page.matchPath is a special key that's used for matching pages
  // only on the client.
  if (page.path.match(/^\/app/)) {
    page.matchPath = `/app/:path`

    // Update the page.
    createPage(page)
  }
}