【问题标题】:Formik onChange executing but not changing Field Value?Formik onChange 执行但不更改字段值?
【发布时间】:2021-04-27 20:08:31
【问题描述】:

大家好,我想我有一个奇怪的问题。我有一个使用 Select 字段的 Formik 表单。我希望它在以下情况下运行:

选择 A 允许您选择一个县 选择 C ​​允许您选择城市。

当用户为 Select A 选择不同的选项时,应用应将 Select C 的值重置为“all”或重新获取 Select A 的新城市。如果 Select A == “all”,则不显示选择 C。

我尝试使用 onChange 道具来执行此操作,其中的逻辑可以正常工作....但是分配 onChange 的实际字段不会更改实际值,而是会保留在先前的值上价值。

麻烦的代码如下:

选择一个:


<div className="field">
            <label id="search-region" className="label" htmlFor="region">
              Region
            </label>
            <Field
              name="region"
              as="select"
              labelid="search-region"
              label="Region"
              className="input"
              onChange={(e) => (values.city = "all")}
            >
              <option value="all">All</option>
              {regions.nodes.map((region) => {
                return (
                  <option key={region.id} value={region.name}>
                    {region.name}
                  </option>
                );
              })}
            </Field>
          </div>

选择 C:

{query.region != "all" ? (
            <div className="field">
              <label id="search-cities" className="label" htmlFor="city">
                City in Region
              </label>
              <Field
                name="city"
                as="select"
                labelid="search-cities"
                label="Cities"
                className="input"
              >
                <option value="all">All</option>
                {uniqueData.sort()}
                {uniqueData.map((town) => {
                  return (
                    <option key={town} value={town}>
                      {town}
                    </option>
                  );
                })}
              </Field>
            </div>
          ) : (
            <></>
          )}

感谢您的帮助。完整代码如下:

const handleSubmit = async (values) => {
    console.log("values: ", values);
    const campfeatures = Array.isArray(values.campfeatures)
      ? values.campfeatures.map(({ value }) => value).join(",")
      : (values.campfeatures = "all");

    Router.push(
      {
        pathname: "/camps",
        query: { ...values, campfeatures },
      },
      undefined,
      { shallow: true }
    ).then(async () => {
      refetch();
    });
  };

  const initialValues = {
    region: query.region || "all",
    camptype: query.camptype || "all",
    city: query.city || "all",
    // campfeatures: query.features || "all",
  };

  return (
    <Formik
      initialValues={initialValues}
      enableReinitialize={true}
      onSubmit={handleSubmit}
    >
      {({ values, submitForm }) => (
        <Form>
          <div className="field">
            <label id="search-region" className="label" htmlFor="region">
              Region
            </label>
            <Field
              name="region"
              as="select"
              labelid="search-region"
              label="Region"
              className="input"
              // onChange={(e) => (values.city = "all")}
            >
              <option value="all">All</option>
              {regions.nodes.map((region) => {
                return (
                  <option key={region.id} value={region.name}>
                    {region.name}
                  </option>
                );
              })}
            </Field>
          </div>

          <div className="field">
            <label id="search-type" className="label" htmlFor="camptype">
              Type
            </label>
            <Field
              name="camptype"
              as="select"
              labelid="search-type"
              label="Type"
              className="input"
            >
              <option value="all">All</option>
              {camptypes.nodes.map((camp) => {
                return (
                  <option key={camp.id} value={camp.name}>
                    {camp.name}
                  </option>
                );
              })}
            </Field>
          </div>

          <div className="field">
            <label id="search-feat" className="label" htmlFor="search-feat">
              Features:
            </label>
            <Field
              component={SelectField}
              name="campfeatures"
              labelid="search-feat"
              label="Features"
              options={selectObjects}
            />
          </div>

          {query.region != "all" ? (
            <div className="field">
              <label id="search-cities" className="label" htmlFor="city">
                City in Region
              </label>
              <Field
                name="city"
                as="select"
                labelid="search-cities"
                label="Cities"
                className="input"
              >
                <option value="all">All</option>
                {uniqueData.sort()}
                {uniqueData.map((town) => {
                  return (
                    <option key={town} value={town}>
                      {town}
                    </option>
                  );
                })}
              </Field>
            </div>
          ) : (
            <></>
          )}

          <div className="field">
            <button type="button" className="button" onClick={submitForm}>
              Search Campgrounds
            </button>
          </div>

          <div className="column mt-5 is-full campgroundResults">
            {campResults[0] != "No Campgrounds Found" ? (
              <div className="campgroundresultsHeader">
                <p>Results:</p>
              </div>
            ) : (
              <div className="campgroundresultsHeader">
                <p>No Campground's Found, Please Search Again.</p>
              </div>
            )}
            <CampgroundResults
              campResults={campResults}
              setViewport={setViewport}
              paginationInfo={paginationInfo}
            />
          </div>

          <div className="pageButtons">
            {paginationInfo[0].hasPreviousPage ? (
              <button
                onClick={() => {
                  fetchMore({
                    variables: {
                      first: null,
                      after: null,
                      last: 10,
                      before: paginationInfo[0].startCursor || null,
                    },
                    updateQuery,
                  });
                }}
              >
                Previous Listings
              </button>
            ) : null}

            {paginationInfo[0].hasNextPage ? (
              <button
                onClick={() => {
                  fetchMore({
                    variables: {
                      first: 10,
                      after: paginationInfo[0].endCursor || null,
                      last: null,
                      before: null,
                    },
                    updateQuery,
                  });
                }}
              >
                Next Listings
              </button>
            ) : null}
          </div>
        </Form>
      )}
    </Formik>

【问题讨论】:

    标签: reactjs next.js formik


    【解决方案1】:

    我想通了,您还必须为该字段设置字段值。

     onChange={(e) => {
                    setFieldValue("city", "all"),
                      setFieldValue("region", e.target.value);
                  }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 2017-12-06
      • 1970-01-01
      相关资源
      最近更新 更多