在React中提交后重定向

时间:2018-11-06 11:14:27

标签: javascript reactjs react-router

在我的应用程序中按下提交按钮后,我试图重定向用户,但是重定向从未发生。提交按钮后,我要通过axios将数据发送到API,然后要重定向。这是通过在构造函数中先将重定向状态设置为false来完成的,在发送了axios调用后,我试图将其状态设置为true,然后如果该值为true,则有条件地呈现一个React Router重定向。

我已经确认Axios实际上将数据发送到后端。但是不知道为什么在将值设置为true后为什么不执行条件渲染。有任何想法吗? :)

我的代码:

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;

1 个答案:

答案 0 :(得分:3)

假设您正在使用react-router v4,则需要使用历史对象进行导航。

None