更新 object 数组中的值 React hooks 方式
Update object value in array React hooks way
如何使用挂钩状态设置更新特定 ID 的标题。这里:
const NotesContainer = ({
}) => {
const [notesDummyData, setNotesDummyData] = useState([
{
id: '5',
title: 'Sauna',
},
{
id: '7',
title: 'Finland',
},
]);
const onChangeItemName = (newTitle, oldTitle, itemId) => {
//Update a new title here for id 7
};
找不到 setState 挂钩的任何示例。
您可以使用 Array.map()
。对于每个项目,检查 id
是否等于 itemId
。如果是这样,展开该项目,并替换 title
。如果没有,return 原项目:
const onChangeItemName = (title, itemId) => {
setNotesDummyData(notesDummyData.map(o => o.id === itemId ? ({
...o,
title
}) : o));
};
只需映射项目,如果 ID 等于所选 ID,您只修改值:
const onChangeItemName = (newTitle, oldTitle, itemId) => {
setNotesDummyData(notesDummyData.map(x => {
if(x.id !== itemId) return x
return {...x, title: newTitle}
}))
}
使用 React Hook 更新数据很容易,但无法正常工作 setState()
,因此可以正常工作 [notThis, thisOne(setNotesDummyDate)]
来更新您的数据。
const [notesDummyData, setNotesDummyData] = useState([
{
id: '5',
title: 'Sauna',
},
{
id: '7',
title: 'Finland',
},
]);
使用React Hook方法更新数据:
const onChangeItemName = (newTitle, oldTitle, itemId) => {
setNotesDummyDate = useState([
{
id: itemId, // Update
title: newTitle,
},
{
id: itemId, // Update
title: newTitle,
},
]);
}
仍然好奇,study here about useState()
加油!
如何使用挂钩状态设置更新特定 ID 的标题。这里:
const NotesContainer = ({
}) => {
const [notesDummyData, setNotesDummyData] = useState([
{
id: '5',
title: 'Sauna',
},
{
id: '7',
title: 'Finland',
},
]);
const onChangeItemName = (newTitle, oldTitle, itemId) => {
//Update a new title here for id 7
};
找不到 setState 挂钩的任何示例。
您可以使用 Array.map()
。对于每个项目,检查 id
是否等于 itemId
。如果是这样,展开该项目,并替换 title
。如果没有,return 原项目:
const onChangeItemName = (title, itemId) => {
setNotesDummyData(notesDummyData.map(o => o.id === itemId ? ({
...o,
title
}) : o));
};
只需映射项目,如果 ID 等于所选 ID,您只修改值:
const onChangeItemName = (newTitle, oldTitle, itemId) => {
setNotesDummyData(notesDummyData.map(x => {
if(x.id !== itemId) return x
return {...x, title: newTitle}
}))
}
使用 React Hook 更新数据很容易,但无法正常工作 setState()
,因此可以正常工作 [notThis, thisOne(setNotesDummyDate)]
来更新您的数据。
const [notesDummyData, setNotesDummyData] = useState([
{
id: '5',
title: 'Sauna',
},
{
id: '7',
title: 'Finland',
},
]);
使用React Hook方法更新数据:
const onChangeItemName = (newTitle, oldTitle, itemId) => {
setNotesDummyDate = useState([
{
id: itemId, // Update
title: newTitle,
},
{
id: itemId, // Update
title: newTitle,
},
]);
}
仍然好奇,study here about useState()
加油!