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

时间:2019-07-08 22:21:45

标签: javascript reactjs gatsby formik

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

当前,我正在axios的{​​{1}}函数中使用withFormik()进行GET调用。收到响应后,我应该可以在UI上对其进行更新。

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

任何人都可以帮忙,让我知道我在这里做错了什么吗?抱歉,这个问题听起来很傻。

这是我的代码的摘录。

handleSubmit()

1 个答案:

答案 0 :(得分:1)

对您的代码做了一些修改:@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