如何解决与返回函数处理函数的处理函数进行反应-使用该函数有什么好处?
我正在编写一个将Checkboxes
中的Categories
呈现为大型系统一部分的组件,代码如下:
import React,{ useState,useEffect } from 'react';
const Checkbox = ({ categories,handleFilter }) => {
const [checked,setChecked] = useState([]);
// get all the categories that user clicked and send them to the Backend
const handleToggle = c => () => {
const currentCategoryId = checked.indexOf(c); // return the first index with cateogry 'c
const newCheckedCategoryId = [...checked];
// if currently checked wasn't already in Checked state ==> Push
// else Pull it
// User want to Check
if (currentCategoryId === -1) {
// not in the state
newCheckedCategoryId.push(c);
}
else {
// User wants to Uncheck
newCheckedCategoryId.splice(currentCategoryId,1); // remove it from the array
}
// console.log(newCheckedCategoryId);
setChecked(newCheckedCategoryId);
handleFilter(newCheckedCategoryId,'category');
}
return (
<>
{
categories.map((cat,index) => (
<li key={index} className='list-unstyled'>
<input
onChange={handleToggle(cat._id)}
value={checked.indexOf(cat._id) === -1}
type='checkbox'
className='form-check-input' />
<label className='form-check-label'>{cat.name}</label>
</li>
))
}
</>
)
};
export default Checkbox;
每当用户单击Checkboxes
之一时,就会调用处理程序handleToggle
。
我不明白为什么我需要使用咖喱函数?
当我尝试使用时:
const handleToggle = c => { ... }
代替:
const handleToggle = c => () => { ... }
反应次数:
Unhandled Rejection (Error): Too many re-renders. React limits the number of renders to prevent an infinite loop.
这是怎么回事,为什么需要使用curried函数?
解决方法
主要问题是handleToggle
已被评估并将该函数的结果分配给onChange
而不是作为回调函数传递。
基于此,您需要将调用函数handleToggle
的方式更改为:
onChange={() => handleToggle(cat._id)}
根据您的示例:
onChange={handleToggle(cat._id)}
最后const handleToggle = c => { ... }
就好了。
根据您的onChange
函数,您直接调用函数而不是分配函数:
onChange={handleToggle(cat._id)} <- Call as soon as this sees
相反,您必须这样做:
onChange={() => handleToggle(cat._id)}
并像这样定义handleToggle
:
// get all the categories that user clicked and send them to the Backend
const handleToggle = c => {
const currentCategoryId = checked.indexOf(c); // return the first index with cateogry 'c
const newCheckedCategoryId = [...checked];
// if currently checked wasn't already in Checked state ==> Push
// else Pull it
// User want to Check
if (currentCategoryId === -1) {
// not in the state
newCheckedCategoryId.push(c);
}
else {
// User wants to Uncheck
newCheckedCategoryId.splice(currentCategoryId,1); // remove it from the array
}
// console.log(newCheckedCategoryId);
setChecked(newCheckedCategoryId);
handleFilter(newCheckedCategoryId,'category');
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。