首页 > 解决方案 > 如何使用复选框将数据写入数组?

问题描述

我有这个代码

const [selectedStudents, setSelectedStudents] = useState([])
const studentsChangeHandler = (e) => {
  setSelectedStudents({...selectedStudents,[e.target.id]:e.target.value});
  console.log('selectedStudents is ',selectedStudents)
};

并在网站上

<input
  type="checkbox"
  id={index}
  value={student._id}
  onChange={studentsChangeHandler}
/>

当我选择网站上的第一个复选框时,什么都没有写,但是第二个被写了,为什么?

第一的

第二

标签: javascriptreactjsmern

解决方案


一般来说setState or useState,React 是异步的。因此,一旦我们更新状态,我们将无法捕获更新的状态。

在钩子中,更新的状态将仅在下一次渲染中可用。因此,为了查看状态是否正在更新,我们可以使用useEffect钩子。以下是相同的示例。

const { useState, useEffect } = React;

const App = () => {
  const [students, setStudents] = useState([]);
  
  const onChangeHandler = event => {
    const {target: {id, value}} = event;
    setStudents(prevStudents => {
      //Push the new object with the id as key and value 
      //of the checkbox as value in the array.
      //In your case the value will be the student id. 
      //But here for simplicity I have used 1, 2 as ids & values
      return [...prevStudents, {[id]: value}]
    });
  }
  
  //To print the initial state as well as whenever the state(i.e., students gets updated
  useEffect(() => {
    console.log(students);
  }, [students])
  
  return (
   <div>
    <div>
      <input type="checkbox" id="1" value="1" onChange={onChangeHandler}/>
      <span>Input 1</span>
    </div>
    <div> 
     <input type="checkbox" id="2" value="2" onChange={onChangeHandler}/>
     <span>Input 2</span>
    </div>
   </div>
  )
}

ReactDOM.render(<App />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>

<div id="react"></div>

注意:出于演示目的,我没有考虑在复选框未选中时从状态中删除对象。我只是添加一个新对象,id其键和值value与数组中的一样,而与复选框的状态无关。因此,请onChangeHandler根据您的需要更新逻辑。


推荐阅读