面临在状态中存储值的问题,并且第三次状态未在 React JS 中更新

facing issue to store value in state and 3rd time state is not updating in react js

我正在尝试从单选按钮获取值,问题是我可以获取值,但是当我尝试存储我的状态时,它仅在第 3 次尝试更新状态后更新 2 次不更新。

单选按钮代码。

              <li>
                <label className="container_radio">
                  Small
                  <span>+ </span>
                  <input
                    type="radio"
                    required
                    onChange={(e) => handleChange(e, product)}
                    defaultValue={5}
                    name={"size"}
                  />
                  <span className="checkmark"></span>
                </label>
                <label className="container_radio">
                  Medium
                  <span>+ </span>
                  <input
                    type="radio"
                    required
                    onChange={(e) => handleChange(e, product)}
                    defaultValue={10}
                    name={"size"}
                  />
                  <span className="checkmark"></span>
                </label>
                <label className="container_radio">
                  Large
                  <span>+ </span>
                  <input
                    type="radio"
                    required
                    onChange={(e) => handleChange(e, product)}
                    defaultValue={15}
                    name={"size"}
                  />
                  <span className="checkmark"></span>
                </label>
              </li>

我正在尝试实现类似这样的输出

[{title: 'Barnes Chapman', options:{Medium size: '5.00' } }]

我的ui:

我的功能:问题在这里 if (isExist) { isExist.options = { ...isExist.options, [name]: value, }; return prevValue; 对于此代码,状态不是无限时间更新。

  const handleChange = (e, product) => {
    // Destructuring
    const { name, value, checked } = e.target;

    console.log(`${value} is ${checked} `);

    // Case 1 : The user checks the box
    if (checked) {
      setProductInfo((prevValue) => {
        const isExist = prevValue.find((item) => item.title === product.title);
        if (isExist) {
          isExist.options = {
            ...isExist.options,
            [name]: value,
          };
          return prevValue;
        } else {
          return [
            ...prevValue,
            {
              title: product.title,
              options: { [name]: value },
            },
          ];
        }
      });
    }

    // Case 2  : The user unchecks the box
    else {
      setProductInfo(productinfo.filter((e) => e.title !== name));
    }
  };

您的代码中几乎没有问题。

1.不要直接改变状态变量。

在下面的代码中,您试图直接更改 state 变量。这可能会导致意外结果。

const isExist = prevValue.find((item) => item.title === product.title);
if (isExist) {
  isExist.options = {
    ...isExist.options,
    [name]: value,
  };
  return prevValue;
}

您可以阅读更多相关信息。

2。在此代码中,您应该通过 title 而不是 name 来比较数组项。 因为你正在使用 title.

    // Case 2  : The user unchecks the box
    else {
      setProductInfo(productinfo.filter((e) => e.title !== name));
    }

3。根据您在 codesandbox

中的代码更新了代码
import { useState } from "react";
import Select from "react-select";
import "./styles.css";

export default function App() {
  const [productinfo, setProductInfo] = useState([]);

  const handleChange = (e, product) => {
    // Destructuring
    const { name, value, checked } = e.target;

    console.log(`${value} is ${checked} ${product.title}`);

    // Case 1 : The user checks the box
    if (checked) {
      setProductInfo((prevValue) => {
        const newValue = prevValue ? [...prevValue] : [];
        const isExist = newValue.find((item) => item.title === product.title);
        if (isExist) {
          isExist.options = {
            ...isExist.options,
            [name]: value,
          };
          return newValue;
        } else {
          return [
            ...newValue,
            {
              title: product.title,
              options: { [name]: value },
            },
          ];
        }
      });
    }

    // Case 2  : The user unchecks the box
    else {
      setProductInfo(productinfo.filter((e) => e.title !== product.title));
    }
  };
  console.log(productinfo, "state");

  return (
    <div className="App">
      <ul className="clearfix">
        {/* {product.options.map((option, i) => {
                return ( */}
        <li>
          <label className="container_radio">
            Small
                  <span>+ </span>
            <input
              type="radio"
              required
              onChange={(e) => handleChange(e, { title: "title" })}
              defaultValue={5}
              name={"size"}
            />
            <span className="checkmark"></span>
          </label>
          <label className="container_radio">
            Medium
                  <span>+ </span>
            <input
              type="radio"
              required
              onChange={(e) => handleChange(e, { title: "title" })}
              defaultValue={10}
              name={"size"}
            />
            <span className="checkmark"></span>
          </label>
          <label className="container_radio">
            Large
                  <span>+ </span>
            <input
              type="radio"
              required
              onChange={(e) => handleChange(e, { title: "title" })}
              defaultValue={15}
              name={"size"}
            />
            <span className="checkmark"></span>
          </label>
        </li>
        {/* ); */}
        {/* // })} */}
      </ul>
    </div>
  );
}