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

问题描述 投票:1回答:2

我使用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};
}
reactjs redux-form react-router-dom
2个回答
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('/')

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.