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. 這也可以作為參數傳遞嗎?
添加回答
舉報