在 React 中提交后重定向 [英] Redirect after submit in React

查看:16
本文介绍了在 React 中提交后重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I'm trying to redirect the user after a submit button has been pressed in my react app, but redirect never happens. After submit button I'm sending data via axios to an API, then I want to redirect. This is done by having first set the state for redirect to false in my constructor, after having sent the axios call I'm trying to set it's state to true then conditionally render a react router redirect if the value is true.

I have confirmed that Axios actually sends data to the back end. But no idea why the conditional render does not run after the value is set to true. Any ideas? :)

My code:

import React from 'react';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import axios from 'axios';
import { Redirect } from 'react-router';

class confirmWithdraw extends React.Component {
  constructor() {
    super();
    this.state = {
      redirect: false
    };

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleEvent = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

  handleSubmit = e => {
    e.preventDefault();
    const amount = sessionStorage.getItem('amount');
    const serverCardNumber = sessionStorage.getItem('cardnumber');
    axios({
      method: 'post',
      url: '/api/whidrawal',
      data: {
        amount,
        serverCardNumber
      }
    }).then(() => this.setState({ redirect: true }));
  };

  render() {
    const { redirect } = this.state;
    if (redirect) {
      return <Redirect to="/moneyform" />;
    }
    return (
      <React.Fragment>
        {redirect ? <Redirect to="/moneyform" /> : null}
        <div>
          Select action -> Withdraw -> <b>Confirm -></b> Take cash -> Finished? -> Take card{' '}
        </div>
        <div>{sessionStorage.getItem('amount')}</div>
        <h1>Please confirm the withdraw of {sessionStorage.getItem('amount')} NOK </h1>
        <CssBaseline /> {/*https://material-ui.com/style/css-baseline */}
        <form onSubmit={this.handleSubmit}>
          <br />
          {/* Bytt ut med CSS block elementer eller noe slikt, bytt name på form fields til å hentes via JS  */}
          <div className="container">
            <Button type="submit" variant="contained" color="primary" className="floatRight">
              Confirm
            </Button>
            <Button type="submit" variant="contained" color="secondary" className="floatLeft">
              Cancel
            </Button>
          </div>
        </form>
      </React.Fragment>
    );
  }
}
export default confirmWithdraw;

解决方案

By assuming you are using react-router v4, you will want to use history object to navigate.

import { withRouter } from 'react-router';
...

handleSubmit = () => {
  ...
  this.props.history.push('/moneyform');
}

render() {
  return (
    <ReactFragment>
      <div>
      ...
    </ReactFragment>
  )
}


export default withRouter(confirmWithdraw);

这篇关于在 React 中提交后重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆