在提交反应中重定向到另一个页面

时间:2018-01-04 05:11:13

标签: reactjs redux-form react-router-dom

我使用react-router-dom进行路由,使用redux-form进行验证。 如果表单是原始的或与验证规则不匹配,我做了验证。提交按钮被禁用。如果请求成功发送,我需要这样做。我将其重定向到' /'页。

主要组件页面

import React, {Component} from 'react';
import {Field, reduxForm} from 'redux-form';
import {Link, Redirect} from 'react-router-dom';

import {createPost} from '../actions/index';

//Validation rules here

const renderField = ({input,label,type,className,meta: {touched,error,}}) => (<div className="form-group">
  <label>{label}</label>
  <input {...input} placeholder={label} type={type} className={className}/> {touched && ((error && <span>{error}</span>))}
</div>);

class PostsNew extends Component {

  render() {
    const {handleSubmit, pristine, submitting} = this.props;

    return (<form onSubmit={handleSubmit}>
      <h3>Create a New Post</h3>
      <Field component={renderField} label="Title" type="text" name="title" validate={[required, title]} className="form-control"/>
      <Field component={renderField} label="Category" type="text" name="categories" validate={[required, nan, category]} className="form-control"/>
      <Field component={renderField} label="Content" name="content" validate={[required, textarea]} className="form-control"/>
      <button type="submit" disabled={pristine | submitting} className="btn btn-primary">
        Submit</button>
      <Link to="/" className="btn btn-danger">Cancel</Link>
    </form>);
  }
}

export default reduxForm({
  form: 'PostsNewForm',
  onSubmit: createPost
}, null)(PostsNew);

Redux操作页面

export function createPost(props) {
  const request = axios.post(`${ROOT_URL}/posts${API_KEY}`, props);
  return {type: CREATE_POST, payload: request};
}

2 个答案:

答案 0 :(得分:1)

如果您需要以编程方式重定向您的应用,请尝试使用历史,您将传递给 react-router-dom

<ConnectedRouter history={history}>
  <div>
    <Route exact path="/" component={Home}/>
    <Route path="/about" component={About}/>
    <Route path="/topics" component={Topics}/>
  </div>
</ConnectedRouter>

然后你将在你的组件道具中有一个名为push的函数。你会像这样使用它:

this.props.push('/')

答案 1 :(得分:0)

onSubmitSuccess: (result, dispatch, props) => {
   return props.dispatch(routerActions.push(uri));
}
  

提交成功时将调用的回调函数。

顺便说一句,onSubmit可以返回一个承诺,如果已经解决将触发onSubmitSuccess,如果失败onSubmitFail