简体   繁体   English

在三元运算符 *React* 中更改两块 state

[英]Change two pieces of state inside a ternary operator *React*

Is it suitable to change two pieces of state in a ternary operator or is this something that is best to do using an if-else statement?是否适合在三元运算符中更改两块 state 还是最好使用 if-else 语句?

Everything I try seems to run into issues.我尝试的一切似乎都遇到了问题。

Examples of what I have tried are shown below.我尝试过的示例如下所示。

x === y ? () => {setRating(10); setRank(1)} : console.log("Not found")
x === y ? setRating(10); setRank(1) : console.log("Not found")

What is the difference between this and the following if-else statement?这个和下面的 if-else 语句有什么区别?

if (x === y) {
    setRating(10);
    setRank(1);
} else {
    console.log("Not found")
}

Separate the expressions with the comma operator, and wrap them with parenthesesL用逗号分隔表达式,并用括号括起来

 const fn = x => x? (console.log('true'), console.log('again')): console.log('false') fn(true)

However, you should prefer an if/else statement for readability purposes:但是,出于可读性目的,您应该更喜欢 if/else 语句:

 const fn = x => { if(x) { console.log('true'); console.log('again'); } else { console.log('false'); } } fn(true)

Try something like,尝试类似的东西,

const setData = (index,average)=>{
 setRating(average);
 setRank(index) 
}

and change your ternary operator as并将您的三元运算符更改为

place.name.toUpperCase() === doc.data().place ?setData(index,doc.data().average):console.log("Not found")

You can wrap the call in self executing arrow function but it's not something I would recommend doing as it isn't a good practice.您可以将调用包装在自执行箭头 function 中,但我不建议这样做,因为这不是一个好习惯。

Creating a third function that calls the two function is the recommended way of doing it.创建调用两个 function 的第三个 function 是推荐的方法。

place.name.toUpperCase() === doc.data().place ? (() => 
    setRating(doc.data().average);
    setRank(index))() 
    : console.log("Not found")

You can go with the answer of Ori Dori, However another approach could be separating the two functions in truth block to another function like this:您可以使用 Ori Dori 的答案 go,但是另一种方法可能是将真值块中的两个函数分离到另一个 function 中,如下所示:

place.name.toUpperCase() === doc.data().place ?
    onFound() : console.log("Not found");


function onFound() {
    setRating(doc.data().average);
    setRank(index) 
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM