【问题标题】:how do i execute multiple if/then in onClick ternary function?如何在 onClick 三元函数中执行多个 if/then?
【发布时间】:2021-10-30 01:38:09
【问题描述】:

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

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 会添加到该选项的列表中,如果我取消点击它,它就会被删除。

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

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    不要试图滥用条件运算符来替代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];
        }
    });
    

    【讨论】:

    • 啊谢谢。关于拼接,我应该对索引进行某种过滤吗?
    • 没有关于 choosebypropssetJsonList 在你的代码中的上下文,它如何连接到 choiceOrder,或者你试图用那个语句做什么,所以我可以'真的没说。
    • 如果它是有状态的,并且您想从状态中删除该索引处的元素(并且choiceOrder 具有要删除的元素的相同索引),那么您可能需要setJsonList((_, i) => i !== choiceIndex)跨度>
    • 我会试试的!等2分钟给你答案复选标记哈哈
    • 您可能必须使用 useEffect 回调,其中包含更改的依赖项数组,但如果没有更多关于代码是什么以及您的目标是什么的上下文,则无法确定。
    【解决方案2】:

    我认为为每个处理程序制作一个单独的函数并使用三元运算符来选择要调用的函数会更方便。另外,请参阅this 问题以获得更多解释。

    【讨论】:

    • 即使使用 if/then 转换也是如此吗?
    猜你喜欢
    • 2010-09-08
    • 2011-08-20
    • 2015-05-11
    • 2021-06-06
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 2019-03-17
    相关资源
    最近更新 更多