2

我有一个登录表单,当我点击登录时,URL被更新,但组件不是。 (如本地主机:8080 /的地方,但仍然登录页面上)反应路由器v4组件未载入按钮提交

我的包的版本如下:

  • 反应 - 15.4.2
  • 反应路由器&反应路由器-DOM - 4.1.1
  • Redux的形式 - 6.6.1

这是登录部件

class Login extends React.Component { 
handleFormSubmit = (values) => { 
    this.props.signInUser(values); 
    history.push('/somewhere'); 
}; 
<div> 
    <div> 
     <h2>Log In</h2> 
     <form onSubmit={ this.props.handleSubmit(this.handleFormSubmit) }> 
     <Field name="email" type="text" label="Email"/> 
     <Field name="password" type="password" label="Password"/> 
     <button action="submit">Sign In</button> 
     </form> 
    </div> 
</div> 
... 
} 
export default connect(mapStateToProps, Actions,)(reduxForm({ 
    form: 'login', 
    validate,})(Login)); 

我正在使用history.push因为我有一个共享的历史对象。

我的路线如下:

<Provider store={ store }> 
     <Router history={history}> 
     <App> 
      <Switch> 
      <Route exact path="/" component={ Home }/> 
      <Route path="/login" component={ Login } /> 
      <Route path="/somewhere" component={ Somewhere } /> 
      </Switch> 
     </ App > 
     </Router> 
    </Provider> 

我尝试使用<Redirect>但不能让它开始工作。还尝试使用withRouter,但发现这仅适用于未在路由中声明的组件。

如何在提交表单时重定向到某处组件?

回答

0

我不知道,这是做到这一点的最好办法,但它为我工作:

<form onSubmit={ this.props.handleSubmit(this.handleFormSubmit) }> 
    <Field name="email" type="text" label="Email"/> 
    <Field name="password" type="password" label="Password"/> 
    <button action="submit">Sign In</button> 
    {this.props.user.loggedIn && <Redirect to={'/Somewhere'} />} 
</form> 

鉴于this.props.handleSubmit(this.handleFormSubmit)分派谁切换到真正的loggedIn支柱user的作用。

您必须将user映射到道具,以便组件在user.loggedIn更改时重新呈现。然后<Redirect>将被激活。

+0

想通了,我没有在mapStateToProps中映射道具。非常感谢! – Reactor