【发布时间】:2020-05-18 12:18:12
【问题描述】:
美好的一天!
我今天在使用 formik 时有一个奇怪的经历, 我目前正在开发一个使用 formik 处理表单的应用程序,并将在 formik 的 onSubmit() 函数中执行 API 请求。
除了我使用 API 请求并等待它的回调之外,一切都很顺利。 不知何故,onSubmit 函数内部的东西会正常工作,但 API 回调值不会返回,除非我在应用程序本身中执行 UI 更改(比如在我的屏幕上按随机点来触发 UI 更改)。
这是我的formik的onSubmit函数的外观
onSubmit={values => {
console.log("before")
let response = FunctionWithApiRequest(values);
console.log("after")
response.then((res) => {
console.log(res)
})
}}
这是我的函数,里面有 api 请求
const FunctionWithApiRequest = (credentials) => {
return fetch(`${AppConfig.HOSTNAME}/v2/auth/signup`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(credentials)
})
.then((response) => response.json())
.then((responseJson) => {
return responseJson
})
.catch((error) => {
console.log(error)
});
}
当我执行 UI 更改时,返回“responseJson”只会出现在 onsubmit 函数中(比如单击我的反应本机屏幕中的随机点)
我想知道是什么问题以及导致错误的原因。
感谢您提前回复。
【问题讨论】:
标签: reactjs react-native formik