javascript - Reactjs - 基于复选框的选中/取消选中不正确理解发出 api 请求
问题描述
我在 reactJS 中有一段代码,它将在将来根据检查/取消检查发出 api 请求。现在它只是根据数组中复选框的选中/取消选中来推送/删除 categoryId。
该代码是完美的并且工作正常,但我无法理解某些地方的代码。请帮助我理解它。
代码::
import React, {useState, useEffect} from 'react';
const Checkbox = ({categories}) => {
const [checked, setChecked] = useState([]);
const handleToggle = c => () => {
// returns the first index or -1
const currentIndex = checked.indexOf(c);
const newCheckedCategoryArray = [...checked];
if(currentIndex === -1){
//then push in default state or remove it if its already there.
newCheckedCategoryArray.push(c);
}
else{
newCheckedCategoryArray.splice(currentIndex, 1)
}
setChecked(newCheckedCategoryArray);
console.log(newCheckedCategoryArray);
}
return categories.map((c, i) => (
<li className="list-unstyled" key={i}>
<input type="checkbox" value={checked.indexOf(c._id === -1)}
className="form-check-input" onChange={handleToggle(c._id)}
/>
<label className="form-check-label">{c.name}</label>
</li>
));
}
export default Checkbox;
我不明白的代码如下::那里的“价值”道具逻辑的目的是什么。
<input type="checkbox" value={checked.indexOf(c._id === -1)}
className="form-check-input" onChange={handleToggle(c._id)}
/>
解决方案
查看关于输入类型='复选框'的开发者信息。
简短而甜蜜的版本:
[value 属性是] 一个表示复选框值的 DOMString。这在客户端从未见过,但在服务器上,这是赋予使用复选框名称提交的数据的值。
您显示的代码并不表示 value 属性正在任何地方使用,因此不会给您带来任何问题;你可以删除它,它仍然可以正常工作。(假设值没有在其他地方使用,在另一个函数中)
顺便说一句,你确定这是完美的吗?在我看来,您可能有错字。我觉得
<input type="checkbox" value={checked.indexOf(c._id === -1)}
className="form-check-input" onChange={handleToggle(c._id)}
/>
应该写成
<input type="checkbox" value={checked.indexOf(c._id) === -1}
className="form-check-input" onChange={handleToggle(c._id)}
/>The code you wrote had a T/F statement inside of "indexOf," so you would only ever have searched the checked array for the first instance of a boolean true or a boolean false.
我写的代码会检查你提交的id是否在checked数组中。如果它不在检查数组中,它将返回 true。如果它在检查数组中,它将返回失败。
推荐阅读
- fiware - 无法在 IoT Agent Fiware 中注册命令
- php - PHP 返回 XML 字符串,并将值添加到属性缺失值
- bash - AWS CLI:如何在 aws ssm 发送命令目标中扩展变量?
- php - Finding inner join mysql with array
- php - 在PHP中将两个数组合并在一起?
- android - 如何跨模块共享 Android lintOptions
- apache-spark - 非分区镶木地板数据的谓词下推
- ssh - 在 Windows 上通过 OpenSSH 访问符号链接
- xcode - 使用 sudo 安装 Cocoapods
- java - 读取时拆分文件