javascript - 如何在 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 添加到该选项的列表中,如果我取消单击它,则会将其删除。
但我只是想知道我是否可以在那个三元函数中包含多个语句。
解决方案
不要试图滥用条件运算符来代替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];
}
});
推荐阅读
- laravel - 更新时的 Laravel 图像验证
- android - 需要在本机 C++ 中增加红色像素值
- android - Okhttp websocket 预期 HTTP 101 响应,但使用 Spring Boot 服务器时为“400”
- javascript - 我的 Jquery 代码在数据表第二页上不起作用
- angular - 如何在 mat-select -Angular 中添加所有选择复选框
- selenium - Python Selenuim 崩溃
- c# - 在实体框架 C# 中使用 Lambda 编写多个 Sum() SQL 查询
- netlogo - 如何调整文件(删除[])以在NetLogo中导出结果?
- python - 从库(Tk)中取消绑定的正确方法是什么?
- python - 如何使用 bs4 打印第一个 google 搜索结果链接?