如何重定向到表单提交的另一个页面?

时间:2019-05-02 16:50:36

标签: reactjs react-router

发布表单后,我试图重定向到某个页面,但它不会重定向,它只会发布表单数据,而不会重定向到指定页面

我尝试附加&&运算符,以便onSubmit可以同时执行这两个功能,但无济于事。我也尝试过同时使用“ onSubmit”和“ onClick”,但只有“ onSubmit”有效

//./userspost.js
import React, { Component } from "react";
import { Redirect, Link } from "react-router-dom";
import Form1 from "./form1";
import { createUsers } from "./actions/appactions";

class userspost extends Component {
  state = {
    redirect: false
  };
  setRedirect = () => {
    this.setState({
      redirect: true
    });
  };
  renderRedirect = () => {
    if (this.state.redirect) {
      return <Redirect to="/users" />;
    }
  };
  handleSubmit(data) {
    console.log("form submission data", data);
    createUsers(data);
  }
  render() {
    return (
      <div>
        {this.renderRedirect()}
        <Form1 onSubmit={this.handleSubmit && this.setRedirect} />
      </div>
    );
  }
}

export default userspost;

用于过帐表单数据

//./form1.js
import React from "react";
import { Link } from "react-router-dom";
var createReactClass = require("create-react-class");
const Form1 = createReactClass({
  //setting initial state
  getInitialState() {
    return {
      firstName: this.props.firstName,
      lastName: this.props.lastName,
      userName: this.props.userName,
      role: this.props.role
    };
  },
  handleFirstChange(e) {
    this.setState({
      firstName: e.target.value
    });
  },
  handleLastChange(e) {
    this.setState({
      lastName: e.target.value
    });
  },
  handleUserChange(e) {
    this.setState({
      userName: e.target.value
    });
  },
  handleRoleChange(e) {
    this.setState({
      role: e.target.value
    });
  },
  handleSubmit(e) {
    e.preventDefault();
    this.props.onSubmit(this.state);
  },
  render() {
    return (
      <form
        name="categories_post"
        className="form-horizontal"
        onSubmit={this.handleSubmit}
      >
        <div id="categories_post">
          <div className="form-group">
            <label
              className="col-sm-2 control-label required"
              htmlFor="firstName"
            >
              First Name
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.firstName}
                onChange={this.handleFirstChange}
                id="firstName"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label
              className="col-sm-2 control-label required"
              htmlFor="lastName"
            >
              Last Name
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.lastName}
                onChange={this.handleLastChange}
                id="lastName"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label
              className="col-sm-2 control-label required"
              htmlFor="userName"
            >
              UserName
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.userName}
                onChange={this.handleUserChange}
                id="userName"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <label className="col-sm-2 control-label required" htmlFor="role">
              Role
            </label>
            <div className="col-sm-10">
              <input
                type="text"
                value={this.state.role}
                onChange={this.handleRoleChange}
                id="role"
                required="required"
                className="form-control"
              />
            </div>
          </div>
          <div className="form-group">
            <div className="col-sm-2" />
            <div className="col-sm-10">
              <button
                type="submit"
                id="categoriesSubmit"
                className="btn-default btn"
              >
                submit
              </button>
            </div>
          </div>
          <div className="form-group">
            <div className="col-sm-2" />
            <div className="col-sm-10">
              <button className="btn btn-danger">
                <Link to="/users">Home</Link>
              </button>
            </div>
          </div>
        </div>
      </form>
    );
  }
});
export default Form1;

使用获取API进行发布

//./actions/appactions.js 
import fetch from "isomorphic-fetch";

export function createCategories(data) {
  return fetch("https://localhost:44341/api/categories", {
    method: "POST",
    mode: "cors",
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json"
    }
  })
    .then(res => {
      return res;
    })
    .catch(err => err);
}
export function createUsers(data) {
  return fetch("https://localhost:44341/api/users/create", {
    method: "POST",
    mode: "cors",
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json"
    }
  })
    .then(res => {
      return res;
    })
    .catch(err => err);
}
export function createBusiness(data) {
  return fetch("https://localhost:44341/api/businesslistings/create", {
    method: "POST",
    mode: "cors",
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json"
    }
  })
    .then(res => {
      return res;
    })
    .catch(err => console.log(err));
}

1 个答案:

答案 0 :(得分:0)

问题是您每次都在渲染Redirect组件以及其他JSX。仅渲染<Redirect to="" />应该可以解决您的问题。

class userspost extends Component {
  state = {
    redirect: false
  };
  setRedirect = () => {
    this.setState({
      redirect: true
    });
  };
  handleSubmit(data) {
    console.log("form submission data", data);
    createUsers(data);
  }
  render() {

    if( this.state.redirect ){
       return <Redirect to="users/" />
    }

    return (
      <div>
        {this.renderRedirect()}
        <Form1 onSubmit={this.handleSubmit} />
      </div>
    );
  }
}

此外,在表单onSubmit事件中仅使用handleSubmit函数。由于用&&添加两个函数可能会导致意外结果。并且当一切准备好重定向时,只需调用函数setRedirect

有人已经回答了类似的问题,所以我从那里得到了一些帮助。检查一下:

https://stackoverflow.com/a/43230829/5568741