发布于 5年前

React Router 4 表单提交后重定向示例

表单设置fireRedirect为发起从定向的标记,当表单提交后,更新它的值为fireRedirect=true。当fireRedirect为true时,重定向到原来的页面。

import React, { Component } from 'react'
import { Redirect } from 'react-router'

export default class MyForm extends Component {
  constructor () {
    super();
    this.state = {
      fireRedirect: false
    }
  }

  submitForm = (e) => {
    e.preventDefault()
    this.setState({ fireRedirect: true })
  }

  render () {
    const { from } = this.props.location.state || '/'
    const { fireRedirect } = this.state

    return (
      <div>
        <form onSubmit={this.submitForm}>
          <button type="submit">Submit</button>
        </form>
        {fireRedirect && (
          <Redirect to={from || '/success'}/>
        )}
      </div>
    )

  }
}
©2020 edoou.com   京ICP备16001874号-3