[英]React: How to Pass State on Each Mapped Array Items?
I rendered a list of buttons using Array.map method in a function component.我在函数组件中使用 Array.map 方法渲染了一个按钮列表。 When I tried to pass state to each mapped array items, the rendered results changed all array items at once, instead of one by one.
当我尝试将状态传递给每个映射的数组项时,渲染结果一次更改了所有数组项,而不是一个一个。
Here is my code.这是我的代码。 Am I doing something wrong?
难道我做错了什么? Sorry if the question has been solved in other thread or I used the wrong method.
抱歉,如果问题已在其他线程中解决,或者我使用了错误的方法。 This is my first React project and I am still learning.
这是我的第一个 React 项目,我仍在学习。 It would be very appreciated if someone could advise.
如果有人可以提供建议,将不胜感激。 Thank you!
谢谢!
import React, { useState } from "react"
export default function Comp() {
const [isActive, setActive] = useState(false)
const clickHandler = () => {
setActive(!isActive)
console.log(isActive)
}
const data = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
]
const renderList = items => {
return items.map(item => (
<li key={item.id}>
<button onClick={clickHandler}>
{item.name} {isActive ? "active" : "not active"}
</button>
</li>
))
}
return (
<ul>{renderList(data)}</ul>
)
}
Put the individual item into a different component so that each has its own active
state:将单个项目放入不同的组件中,以便每个组件都有自己的
active
状态:
export default function Comp() {
const data = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
]
const renderList = items => (
items.map(item => <Item key={item.id} name={item.name} />)
);
return (
<ul>{renderList(data)}</ul>
)
}
const Item = ({ name }) => {
const [isActive, setActive] = useState(false);
const clickHandler = () => {
setActive(!isActive);
};
return (
<li>
<button onClick={clickHandler}>
{name} {isActive ? "active" : "not active"}
</button>
</li>
);
};
You need to set the active-id
in handling the click-event
.您需要在处理
click-event
设置active-id
。 That will in-turn render active/non-active conditionally
:这将反过来
active/non-active conditionally
呈现active/non-active conditionally
:
Notice the flow (1) > (2) > (3)
注意流程
(1) > (2) > (3)
function Comp() {
const [activeId, setActiveId] = React.useState(null);
const clickHandler = (item) => {
setActiveId(item.id) // (2) click-handler will set the active id
}
const data = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
]
const renderList = items => {
return items.map(item => (
<li key={item.id}>
<button onClick={() => clickHandler(item)}> // (1) passing the clicked-item so that we can set the active-id
{item.name} {item.id === activeId ?
"active" : "not active" // (3) conditionally render
}
</button>
</li>
))
}
return (
<ul>{renderList(data)}</ul>
)
}
Good Luck...祝你好运...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.