简体   繁体   English

与返回函数(咖喱)的处理程序函数反应 - 使用它有什么好处?

[英]React with a handler function that returns a function (a curried) - what's the benefit of using it?

I'm writing a component that renders Checkboxes of Categories as part of a large system, here is the code:我正在编写一个组件,将Categories Checkboxes呈现为大型系统的一部分,这是代码:

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;

Whenever a user clicks one of the Checkboxes the handler handleToggle is invoked.每当用户单击其中一个Checkboxes ,就会调用处理程序handleToggle

What I don't understand is why I need to use a curried function?我不明白的是为什么我需要使用柯里化函数?

When I try to use:当我尝试使用:

const handleToggle = c => { ... } 

Instead of:代替:

const handleToggle = c => () => { ... } 

React throws:反应抛出:

 Unhandled Rejection (Error): Too many re-renders. React limits the number of renders to prevent an infinite loop.

What's the deal here and why is it required to use a curried function ?这里有什么交易,为什么需要使用柯里化函数?

The main problem is handleToggle has been evaluated and assigned the result of that function to onChange instead of passing as a callback function.主要问题是handleToggle已被评估并将该函数的结果分配给onChange而不是作为回调函数传递。

Based on that you need to change how you call the function handleToggle as:基于此,您需要将调用函数handleToggle方式更改为:

onChange={() => handleToggle(cat._id)}

From your example:从你的例子:

onChange={handleToggle(cat._id)}

And at the end const handleToggle = c => { ... } will be just fine.最后const handleToggle = c => { ... }会很好。

According to your onChange function you are calling function directly instead of assigning it:根据您的onChange函数,您直接调用函数而不是分配它:

onChange={handleToggle(cat._id)} <- Call as soon as this sees

instead you have to do this:相反,你必须这样做:

onChange={() => handleToggle(cat._id)}

And define handleToggle like this:并像这样定义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');
    }


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在React类组件中,使用不带参数的curried函数的目的是什么? - In a react class component what is the purpose of using curried function with no arguments? 在JavaScript中使用(function(){...})()有什么好处 - What is benefit of using (function(){…})() in JavaScript 将async预先添加到返回promise的函数有什么好处? - What is the benefit of prepending async to a function that returns a promise? 内联函数调用有什么好处? - What's the benefit of inline function calls? AWS Lambda:在节点运行时使用异步处理程序 function 是否有好处? - AWS Lambda: Is there a benefit to using an async handler function for the Node runtime? 使用lodash分配功能有什么好处? - What is the benefit of using lodash assign function? 在事件处理程序中反应咖喱箭头函数 - React curried arrow function in event handlers 是否可以流类型一个返回另一个可能被柯里化的函数的函数? - Is it possible to flow type a function that returns another function that may be curried? 如何正确使用带有 react-redux 的 useSelector 钩子的咖喱选择器函数? - How to correctly use a curried selector function with react-redux's useSelector hook? 使用镜头在阵列上映射柯里化函数 - Map a curried function over an array using lenses
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM