首页 > 解决方案 > 如何在 onClick 三元函数中执行多个 if/then?

问题描述

尝试调试,但不确定此结构是否有效...

onClick={()=>{ //2. an image is clicked, and the choice is added to the choiceOrder state, and then a jsonupdate is called -- 3. in ChooseBy.js
   //onclick, add or remove the choice
   choosebyprops.setChoiceOrder( choiceOrder=>
                                    choiceOrder.includes(attrprops.attrChoice)
                                    ?
                                    (
                                    (choiceIndex = choiceOrder.findIndex(attrprops.attrChoice)),
                                    (choiceOrder.filter(list=> list!==attrprops.attrChoice)),
                                    (choosebyprops.setJsonList(jsonList=> jsonList.splice(choiceIndex) )) //removes the json data for that choice
                                    )
                                    :
                                    (
                                    ( [...choiceOrder,attrprops.attrChoice] ),
                                    (choosebyprops.setJsonList(jsonList=> [...jsonList, UpdateJson({...allprops})]))  //adds json data for that choice
                                    )
                                    )
}}

我基本上是在尝试制作一个 json 列表,如果我单击按钮,则会将过滤后的 json 添加到该选项的列表中,如果我取消单击它,则会将其删除。

但我只是想知道我是否可以在那个三元函数中包含多个语句。

标签: javascriptreactjsnext.js

解决方案


不要试图滥用条件运算符来代替if/ else- if/else将允许您创建,这些语句可以更自然地放入其中。

听起来你想要做这样的事情:

choosebyprops.setChoiceOrder(choiceOrder => {
    if (choiceOrder.includes(attrprops.attrChoice)) {
        const choiceIndex = choiceOrder.findIndex(attrprops.attrChoice);
        choosebyprops.setJsonList(jsonList => jsonList.splice(choiceIndex)); // this splice sounds wrong - don't mutate in React
        return choiceOrder.filter(list => list !== attrprops.attrChoice);
    } else {
        choosebyprops.setJsonList(jsonList => [...jsonList, UpdateJson({ ...allprops })]);
        return [...choiceOrder, attrprops.attrChoice];
    }
});

推荐阅读