首页 > 解决方案 > React - 如何在使用 fetch 完成 POST 请求后重定向路径

问题描述

在使用 fetch 完成 POST 请求,我试图重定向到另一个路径。

我在我的状态中设置了一个变量,以便在 POST 函数完成后进行观察

this.state.successfulPOST: false

我是条件渲染,所以如果我this.state.successfulPOST: true,我的重定向会被渲染

问题是我的重定向发生我的 POST 请求之前。我怎样才能使我的 POST 请求/api/account/update/完成,然后在此路径上为我的 GET 请求呈现我的重定向/checkout/shippingaddress

这是我的完整代码:

import React, { Component } from "react";
import "whatwg-fetch";
import cookie from "react-cookies";
import { Redirect } from 'react-router-dom';

class GuestEmailForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      successfulPOST: false,
    };
  }

  updateGuestEmail = (data) => {

    const endpoint = "/api/account/update/"; 
    const csrfToken = cookie.load("csrftoken");

    if (csrfToken !== undefined) {
      let lookupOptions = {
        method: "POST",
        redirect: 'follow',
        headers: {
          "Content-Type": "application/json",
          "X-CSRFToken": csrfToken
        },
        body: JSON.stringify(data),
        credentials: "include"
      };
      fetch(endpoint, lookupOptions)
        .then(response => {
          return response.json();
        })
        .then(responseData => {
          this.setState({email: responseData.email})
        })
        .then( 
          this.setState({successfulPOST: true})
          )
        .catch(error => {
          console.log("error", error);
          alert("An error occured, please try again later.");
        });
    }
  };


  handleEmailChange = event => {
    const { name, value } = event.target;
    this.setState({ [name]: value });
  };

  handleSubmit = (event) => {
    event.preventDefault();
    let data = this.state;

    if (data !== undefined){
        (
          this.updateGuestEmail(data),
          console.log(this.state.email)
        )
    } else {
        ""
    }
  };

  resetSucessfulPOST = () => {
      this.setState({
        successfulPOST: false,
      })
  }


  componentDidMount() {
    this.resetSucessfulPOST()
  }

  render() {

    const {email, successfulPOST} = this.state

    // redirect to shipping page after successful POST of email
    if (successfulPOST === true)  

      return <Redirect push to={{ pathname: '/checkout/shippingaddress'}} />

    else

      return (
        <form onSubmit={this.handleSubmit}>
          <div>            
              <label>
                  Guest Email:
                  <input 
                          className="input" 
                          type="email" 
                          name="email"
                          value={email} 
                          onChange={event => {
                              this.handleEmailChange(event);
                            }}
                          />
              </label>
              <button className="btn btn-primary">Submit</button>

              </div>

        </form>
    );
  }
}

export default GuestEmailForm;

提前非常感谢!

标签: reactjsredirectasync-awaitreact-routerfetch

解决方案


首先,您应该删除该componentDidMount()方法,然后您将

setState({successfulPOST: true})

在 updateGuestEmail 方法结束时,它将重新渲染,并根据您的情况重定向..


推荐阅读