【问题标题】:React - how to Redirect path after completing POST request using fetchReact - 如何在使用 fetch 完成 POST 请求后重定向路径
【发布时间】:2020-03-07 17:33:56
【问题描述】:

我正在尝试重定向到另一个路径之后使用 fetch 完成 POST 请求。

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

this.state.successfulPOST: false

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

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

这是我的完整代码:

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;

提前非常感谢!

【问题讨论】:

    标签: reactjs redirect async-await react-router fetch


    【解决方案1】:

    首先你应该删除componentDidMount() 方法然后 你会

    setState({successfulPOST: true})
    

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

    【讨论】:

    • 谢谢,但我的重新渲染工作正常。问题是我如何才能完成我对 /api/account/update/ 的 POST 请求,然后在此路径/结帐/发货地址上呈现我的 GET 请求的重定向?现在 GET 请求发生在 POST 请求之前并在后端搞砸了。
    【解决方案2】:

    所以我设法找出问题所在。

    而不是这个.then(this.setState({successfulPOST: true}))

    必须是这个 .then(responseData =&gt; {this.setState({successfulPOST: true,});})

    如果你不向.then() 传递参数,那么promise 方面就不起作用,我的setState 会立即被调用。

    【讨论】:

      猜你喜欢
      • 2017-07-25
      • 2012-12-13
      • 2018-09-14
      • 2011-10-01
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      相关资源
      最近更新 更多