3 回答
TA贡献1773条经验 获得超3个赞
为您的帖子请求创建一个函数:
async function POST(url, payload, next) {
setLoading(true)
await axios.post(url, payload)
.then(response => {
setLoading(false)
console.log(response)
let res = response;
if (res.data.id === 11) {
next();
}
})
.catch(error => {
console.log(error)
})
}
然后你可以在你的代码中使用这个函数,如下所示:
const handleSubmitPhoneNumber = (e, next) => {
e.preventDefault();
const payload = {
"phone": user.phone
}
POST("https://jsonplaceholder.typicode.com/users", payload, next)
const handleSubmitVerificationCode = (e, next) => {
e.preventDefault();
const payload = {
"verificationCode": user.verificationCode
}
POST("https://jsonplaceholder.typicode.com/users", payload, next)
}
TA贡献1818条经验 获得超3个赞
1
请尝试这个。
const handleSubmitPhoneNumber = (e, next) => {
e.preventDefault();
const payload = {
"phone": user.phone
}
postMethod("https://jsonplaceholder.typicode.com/users", payload, next);
}
const handleSubmitVerificationCode = (e, next) => {
e.preventDefault();
const payload = {
"verificationCode": user.verificationCode
}
postMethod("https://jsonplaceholder.typicode.com/users", payload, next);
}
const postMethod = async (url, payload, next) => {
setLoading(true)
await axios.post(url, payload)
.then(response => {
setLoading(false)
console.log(response)
let res = response;
if (res.data.id === 11) {
next();
}
})
.catch(error => {
console.log(error)
})
}
TA贡献1874条经验 获得超12个赞
其他答案中表达的想法的稍微简洁的版本可能如下所示:
const postMethod = (url, getPayload) => async (e, next) => {
e.preventDefault();
setLoading(true)
await axios.post(url, getPayload())
.then(response => {
setLoading(false)
console.log(response)
let res = response;
if (res.data.id === 11) {
next();
}
})
.catch(error => {
console.log(error)
})
}
const handleSubmitPhoneNumber = postMethod (
"https://jsonplaceholder.typicode.com/users",
() => {phone: user.phone}
)
const handleSubmitVerificationCode = postMethod (
"https://jsonplaceholder.typicode.com/users",
() => {verificationCode: user.verificationCode}
)
我更喜欢这个的主要原因是这些处理程序的处理方式e在next这些处理程序之间没有变化,因此理想情况下它属于公共代码。
不过,无论是在本文中还是在原版中,我对全球访问user. 这也可以作为参数传递吗?
添加回答
举报