javascript - 如何使用复选框将数据写入数组?
问题描述
我有这个代码
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}
/>
当我选择网站上的第一个复选框时,什么都没有写,但是第二个被写了,为什么?
解决方案
一般来说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
根据您的需要更新逻辑。
推荐阅读
- microsoft-teams - 作为电源自动化解决方案的一部分,为新团队创建频道
- python - 访问 Python/Kivy 动态屏幕类
- java - 需要使用java将所有文件从一个文件夹复制到另一个文件夹
- css - 在长包装词之前防止换行
- google-cloud-platform - 谷歌云函数永久链接
- keycloak - 有没有办法为每个领域定义一个自定义注册 URL?
- apache-spark - 如何摆脱这个错误不匹配的输入'line'期待
spark-sql 中的(第 1 行,第 17 行) - swift - 如何在 Amplify DataStore 中将可选值保存为 1:1 关系
- java - geeksforgeeks 问题上的螺旋矩阵遍历
- c# - 如果无法识别,如何在游戏中模拟硬件鼠标点击?