reactjs - 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;
提前非常感谢!
解决方案
首先,您应该删除该componentDidMount()
方法,然后您将
setState({successfulPOST: true})
在 updateGuestEmail 方法结束时,它将重新渲染,并根据您的情况重定向..
推荐阅读
- ruby-on-rails - Rails:如何获取具有相同关联数组的实例
- c# - 在 Azure 中存储数据以进行绘图
- javascript - 在多值属性javascript中编辑一个值
- sql - 插入不存在对应记录的记录
- java - 自定义声纳规则:当类用作特定方法的参数时需要方法
- sql - Oracle 11g:字符串的 IN 等效项
- android - 片段转换
- .net - ASP.NET MVC DateTimePicker - 好一个
- javascript - 我正在尝试上传视频
- authentication - 是否可以自定义 aws-amplify-react-native 包的默认注册、登录屏幕?