React is not conditionally rendering in listed elements correctly. How do you conditionally render listed items?

huangapple go评论58阅读模式
英文:

React is not conditionally rendering in listed elements correctly. How do you conditionally render listed items?

问题

I know that setting tickets.changeToggle to true (on line 2) will display "hi" in the paragraph html.

I know that hitting the button will change tickets.changeToggle to true or false, depending on the current value of each listed item.

My problem is changing tickets.changeToggle does not remove "hi" in the example below. Even when it is false. I would just setState but I want to only change its on the ticket clicked. I guess I could set an array and track the state by index, but that seems like the wrong way to go. Any ideas on what to do?

{tickets.map((tickets) => {
tickets.changeToggle = true;
<button onClick={() => {tickets.changeToggle = !tickets.changeToggle}>Chg

{tickets.changeToggle && 'hi'}

英文:

I know that setting tickets.changeToggle to true (on line 2) will display "hi" in the paragraph html

I know that hitting the button will change tickets.changeToggle to true or false, depending on the current value of each listed item.

My problem is changing tickets.changeToggle does not remove "hi" in the example below. Even when it is false. I would just setState but i want to only change its on the ticket clicked. I guess I could set an array and track the state by index but that seems like the wrong way to go. Any ideas on what to do?

{tickets.map((tickets) =&gt; {
            tickets.changeToggle = true;
            &lt;button onClick={() =&gt; {tickets.changeToggle = !tickets.changeToggle}&gt;Chg&lt;/button&gt;
            &lt;p&gt;{tickets.changeToggle &amp;&amp; &#39;hi&#39;}&lt;/p&gt;

答案1

得分: 1

你需要将HTML内容括在括号中并返回,因为你在lambda表达式中使用了一个代码块:

{tickets.map((tickets) => {
    tickets.changeToggle = true;
    return (
        <button onClick={() => {tickets.changeToggle = !tickets.changeToggle}}>Chg</button>
        <p>{tickets.changeToggle && 'hi'}</p>
    )
})}

此外,在map表达式中更改数据是一个糟糕的主意。不要这样做。

英文:

You need to wrap the HTML in parenthesis and return, since you're using a lambda with a block:

{tickets.map((tickets) =&gt; {
            tickets.changeToggle = true;
            return (
                 &lt;button onClick={() =&gt; {tickets.changeToggle = !tickets.changeToggle}&gt;Chg&lt;/button&gt;
                 &lt;p&gt;{tickets.changeToggle &amp;&amp; &#39;hi&#39;}&lt;/p&gt;
            )
    })
}

Also, mutating data in a map expression is a horrible idea. Don't do that.

huangapple
  • 本文由 发表于 2023年4月11日 01:36:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979343.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定