英文:
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) => {
tickets.changeToggle = true;
<button onClick={() => {tickets.changeToggle = !tickets.changeToggle}>Chg</button>
<p>{tickets.changeToggle && 'hi'}</p>
答案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) => {
tickets.changeToggle = true;
return (
<button onClick={() => {tickets.changeToggle = !tickets.changeToggle}>Chg</button>
<p>{tickets.changeToggle && 'hi'}</p>
)
})
}
Also, mutating data in a map expression is a horrible idea. Don't do that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论