【发布时间】: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