Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

limit reactjs input element of type checkbox to 2 checked while using usestate array

my purpose is to allow two days of the week to be a weekend

the problem is with this approach i am unable to limit the weekend array to hold only two days its always going beyond

i think the problem is that the state is async and setState and useEffect are having different values but unable to solve the problem

const weekendDays = [
    "Saturday",
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
  ];
const [weekend, setWeekend] = useState([]);

const handleWeekendSelection = ({ target }) => {
    if (target.checked) {
      !weekend.includes(target.value) &&
        setWeekend((prev) => [...prev, target.value]);
    } else {
      setWeekend((prev) => [...prev].filter((day) => day !== target.value));
    }
  };

  useEffect(() => {
    console.log(weekend.length);
    if (weekend.length > 2) {
      const checkboxes = document.querySelectorAll(
        "input[type=checkbox]:checked"
      );
      const lastCheckbox = checkboxes[checkboxes.length - 1];
      lastCheckbox.checked = false;
setWeekend((prev) => {
        const correctedWeekend = prev;
        correctedWeekend.length > 2 && correctedWeekend.pop();
        return [...correctedWeekend];
  });
    }
  }, [weekend.length]);

        <div>
          {weekendDays.map((day, index) => {
            return (
              <div key={index}>
                <input
                  type="checkbox"
                  value={index}
                  onChange={handleWeekendSelection}
                />
                <label>{day}</label>
              </div>
            );
          })}
        </div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Instead of using useEffect it would be proper to handle it while setting in the state. Something like this

const handleWeekendSelection = ({ target }) => {
    if (target.checked) {
      if(!weekend.includes(target.value)){
        let newWeekend = [...weekend, target.value]
        if(weekend.length === ) newWeekend = [weekend[1], target.value]
        setWeekend(newWeekend);
      }
        
    } else {
      setWeekend((prev) => [...prev].filter((day) => day !== target.value));
    }
  };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...