如何使用 useState 仅更新单击的元素?
我有一个包含步骤列表的章节列表。我试图在单击按钮时向章节添加步骤,但目前我正在向所有章节添加步骤。 我做错了什么?
const dummy_chapters = [
{ id: 1, title: 'Chapter 1'},
{ id: 2, title: 'Chapter 2'},
{ id: 2, title: 'Chapter 3'},
]
const dummy_steps = [
{ id: 1, title: 'Step 1'},
{ id: 2, title: 'Step 2'},
]
const [chapters, setChapters] = React.useState(dummy_chapters)
const [steps, setSteps] = React.useState(dummy_steps)
const addStep = () => {
setSteps([
...steps,
{
id: 5,
title: 'Another step'
},
])
}
return (
<List>
{chapters.map((d, idx) => (
<ChapterListItem
secondaryAction={
<IconButton onClick={addStep}>
<MoreVertIcon/>
</IconButton>
}>
</ChapterListItem>
<List component='div' disablePadding>
{steps?.map((d, idx) => (
<ListItemText primary={d.title}/>
))}
</List>
))}
</List>
<Icon onClick={addChapter} iconId='add' />
</Box>
</>
)
}
I have a list of chapters that have a list of steps. I am trying to add a step to a chapter when clicking the button, but I am currently adding a step to all of the chapters instead.
What am I doing wrong?
const dummy_chapters = [
{ id: 1, title: 'Chapter 1'},
{ id: 2, title: 'Chapter 2'},
{ id: 2, title: 'Chapter 3'},
]
const dummy_steps = [
{ id: 1, title: 'Step 1'},
{ id: 2, title: 'Step 2'},
]
const [chapters, setChapters] = React.useState(dummy_chapters)
const [steps, setSteps] = React.useState(dummy_steps)
const addStep = () => {
setSteps([
...steps,
{
id: 5,
title: 'Another step'
},
])
}
return (
<List>
{chapters.map((d, idx) => (
<ChapterListItem
secondaryAction={
<IconButton onClick={addStep}>
<MoreVertIcon/>
</IconButton>
}>
</ChapterListItem>
<List component='div' disablePadding>
{steps?.map((d, idx) => (
<ListItemText primary={d.title}/>
))}
</List>
))}
</List>
<Icon onClick={addChapter} iconId='add' />
</Box>
</>
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在每个
章节
内添加steps
键,而不是以不同的方式管理章节
和步骤
。然后,要添加新步骤,您可以尝试如下所述的方法。Instead of managing
chapters
andsteps
differently you can addsteps
key inside of eachchapters
. Then for adding new steps you can try approach as mentioned below.尝试在步骤对象中添加一个字段(例如
chapterId: 1
),然后在递增之前添加一个条件以在递增之前检查章节 ID。这样您就可以增加所需章节的步骤。
Try adding a field (like
chapterId: 1
in your steps object, and then before incrementing add a condition to check chapter id before increment.That way you can increment steps for the chapter you want.