【问题标题】:React Router v4 Component not loaded on button submit按钮提交时未加载 React Router v4 组件
【发布时间】:2017-09-23 10:03:31
【问题描述】:

我有一个登录表单,当我单击登录时,URL 会更新,但组件不会。 (例如 localhost:8080/somewhere 但仍在登录页面上)

我的包的版本如下:

  • 反应 - 15.4.2
  • react-router & react-router-dom - 4.1.1
  • redux-form - 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>

我尝试使用&lt;Redirect&gt;,但无法正常工作。也尝试使用withRouter,但发现这仅适用于未在路由中声明的组件。

提交表单时如何重定向到Somewhere组件?

【问题讨论】:

    标签: react-router react-redux redux-form react-router-redux react-router-v4


    【解决方案1】:

    我不确定这是不是最好的方法,但它对我有用:

    <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 ) 调度了一个动作,该动作将userloggedIn 属性切换为true。

    您必须将user 映射到道具,以便您的组件在user.loggedIn 更改时重新渲染。然后将激活&lt;Redirect&gt;

    【讨论】:

    • 发现我没有在mapStateToProps中映射道具。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多