React-如何在使用fetch完成POST请求后重定向路径



在使用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;

提前感谢!

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

setState({successfulPOST: true})

在updateGuestMail方法结束时,它将重新渲染,并根据您的条件重定向。。

所以我设法解决了这个问题。

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

应该是这样.then(responseData => {this.setState({successfulPOST: true,});})

事实证明,如果你不把一个参数传递到.then()中,promise方面就不起作用,我的setState会立即被调用。

最新更新