gpt4 book ai didi

javascript - 如何在 react Hook 中正确更新状态

转载 作者:行者123 更新时间:2023-12-04 03:51:23 25 4
gpt4 key购买 nike

所以,问题是每当我按下删除按钮时,它只会删除删除最后一个输入和按钮,而不考虑索引。我试图将 key 更改为 key={${index}${name}}`,这不会很好地工作,因为输入是可变的(在主代码中)并且把事情搞砸了。如何根据索引正确删除?

function App() {
const [names, setNames] = React.useState(["First", "Second",'third','fourth']);
const onNameDelete = useCallback((index: number) => {
setNames((prev) => {
const name = names[index];
return prev.filter(x => x != name);
});
}, [names]);

return (
<div>
{names.map((name, index) => (
<Child
key={index}
name={name}
index={index}
onDelete={onNameDelete}
/>
))}
</div>
);
}
interface ChildProps {
name: string;
index: number;
onDelete: (index: number) => void;
}

export const Child: React.FC<ChildProps> = React.memo(
({ name, index, onDelete }) => {
return (
<div>
<input
defaultValue={name}
/>
<button onClick={() => onDelete(index)}>delete</button>
</div>
);
}

最佳答案

这里是:

function App() {
const [names, setNames] = React.useState(
["First", "Second",'third','fourth'].map((name, index) => ({ id: index, name }))
);
const onNameDelete = useCallback((index: number) => {
setNames((prev) => prev.filter({ id } => id !== index));
}, [names]);

return (
<div>
{names.map(({ id, name }) => (
<Child
key={id}
name={name}
index={id}
onDelete={onNameDelete}
/>
))}
</div>
);
}
interface ChildProps {
name: string;
index: number;
onDelete: (index: number) => void;
}

export const Child: React.FC<ChildProps> = React.memo(
({ name, index, onDelete }) => {
return (
<div>
<input
defaultValue={name}
/>
<button onClick={() => onDelete(index)}>delete</button>
</div>
);
}

请使用对象数组代替存储名称的数组:

const [names, setNames] = React.useState(
["First", "Second",'third','fourth'].map((name, index) => ({ id: index, name }))
);

关于javascript - 如何在 react Hook 中正确更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64395726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com