如何使用复选框将数据写入数组?

问题描述

我有这个代码

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}
/>

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

first

second

解决方法

通常,React 中的 setState or useState 是异步的。因此,一旦我们更新状态,我们将无法在其中捕获更新的状态。

在钩子中,更新的状态将仅在下一次渲染中可用。因此,为了查看状态是否正在更新,我们可以使用 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 逻辑。

,

你可以用jquery来做。本示例通过选择器选择选中的复选框,然后对每个元素调用 .each() 方法,最后将它们推送到数组中。

<!DOCTYPE html>
<html>
  
<head>
    <title>
        JQuery | Get all selected checkboxes in an array.
    </title>
    <style>
        #GFG_UP {
            font-size: 17px;
            font-weight: bold;
        }
          
        #GFG_DOWN {
            color: green;
            font-size: 24px;
            font-weight: bold;
        }
          
        button {
            margin-top: 20px;
        }
    </style>
</head>
<script src=
    "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
  
<body style="text-align:center;" id="body">
    <h1 style="color:green;">  
            Geek
        </h1>
    <p id="GFG_UP">
    </p>
      
    <input type="checkbox" name="type" value="GFG" /> GFG:
    <input type="checkbox" name="type" value="Geeks" /> Geeks:
    <input type="checkbox" name="type" value="Geek" /> Geek:
    <input type="checkbox" name="type" value="portal" /> portal:
    <br>
    <button>
        click here
    </button>
    <p id="GFG_DOWN">
    </p>
    <script>
        $('#GFG_UP')
        .text('First check few elements then click on the button.');
        $('button').on('click',function() {
            var array = [];
            $("input:checkbox[name=type]:checked").each(function() {
                array.push($(this).val());
            });
            $('#GFG_DOWN').text(array);
        });
    </script>
</body>
  
</html>