React Forms:根据 withFormik() 中的 Axios GET 调用响应更新 UI

React Forms: Updating the UI based on the Axios GET call response in withFormik()

我正在使用 withFormik() 在我的 Gatsby 应用程序中构建表单。

目前,我正在使用 withFormik()handleSubmit() 函数中的 axios 进行 GET 调用。收到回复后,我应该可以在 UI.

上更新它

这里的问题是,在 UI 上单击“搜索”按钮两次后数据正在更新,而不是在单击后立即更新。

谁能帮忙告诉我我做错了什么?如果这个问题听起来很愚蠢,我们深表歉意。

这是我的代码的摘录。

import React from "react"
import { withFormik, Form, Field } from "formik"
import axios from "axios"

const FormComponent = ({ values, errors }) => (
  <div>
    <Form>
      <label># </label>
      <Field className="HashtagInput" type="text" name="hashtag" />
      <button className="SearchBtn" type="submit"></button>
    </Form>
    <p className="SearchResult">{values.hashtagSearchResult}</p>
  </div>
)

const FormikApp = withFormik({
  mapPropsToValues() {
    return {
      hashtag: "",
      hashtagSearchResult: [], // 
    }
  },
  handleSubmit(values) {
    console.log("$ Search button clicked!")
    let hashtag = values.hashtag
    let hashtagResult = []
    let url = "https://jsonplaceholder.typicode.com/todos/" + hashtag + "/"
    axios.get(url).then(res => {
      let hashtags = searchHashtags(res.data)
      ...
      console.log("$ Hashtag result - " + hashtagResult)
      values.hashtagSearchResult = hashtagResult;
    })
    ...
})(FormComponent)

对你的代码做了一点修改:@Pavan

我做的主要事情是使用 setSubmitting(true);

我还在表单中添加了一个 onSubmit={handleSubmit}

import React from "react";
import ReactDOM from "react-dom";
import { withFormik, Form, Field } from "formik";
import axios from "axios";

const FormComponent = ({ values, errors, handleSubmit }) => (
  <div>
    <Form onSubmit={handleSubmit}>
      <label># </label>
      <Field className="HashtagInput" type="text" name="hashtag" />
      <button className="SearchBtn" type="submit">
        search
      </button>
    </Form>
    <p className="SearchResult">{values.hashtagSearchResult.toString()}</p>
  </div>
);

const FormikApp = withFormik({
  mapPropsToValues() {
    return {
      hashtag: "",
      hashtagSearchResult: [] //
    };
  },
  async handleSubmit(values, { setSubmitting }) {
    console.log("$ Search button clicked!");
    let hashtag = values.hashtag;

    setSubmitting(true);
    let url = "https://jsonplaceholder.typicode.com/todos/" + hashtag + "/";
    const c = await axios.get(url);

    console.log("$ update");
    values.hashtagSearchResult = [...values.hashtagSearchResult, c.data.title];

    setSubmitting(false);
  }
})(FormComponent);

const rootElement = document.getElementById("root");
ReactDOM.render(<FormikApp />, rootElement);



https://codesandbox.io/s/brave-lake-p8cf2