【问题标题】:React Native Formik handleSubmit does not read return values from functionReact Native Formik handleSubmit 不从函数读取返回值
【发布时间】: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


    【解决方案1】:

    您可能可以在一个单独的函数中使用 await 和 async 执行此操作。例如

    async handleSubmit(){
    let {credentials} = this.state
    let data = await this.props.FunctionWithApiRequest(credentials)
    this.setState({returnedData: data})
    }
    

    现在在你的 textInput/formik 中

    onSubmit={()=>this.handleSubmit()}
    

    我假设你已经在actions.file中创建了请求api函数,而不是在同一个文件中。我对吗?所以我所做的只是在调用之前放置await。这意味着下一行只有在你有响应时才会执行已退回。如果您有任何问题,请发表评论。

    【讨论】:

    • 我尝试了这种语法,但它返回的结果与上面的相同。在 console.log(return_value) 出现之前,我仍然需要触摸或执行某些操作
    【解决方案2】:

    这是由运输捆绑器引起的,当您启用挖掘模式时。

    【讨论】:

      猜你喜欢
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 2021-09-09
      • 2020-11-20
      相关资源
      最近更新 更多