如何在React Hooks中正确地更新状态

3
所以,问题是每当我按下删除按钮时,它只会删除最后一个输入和按钮,而不管索引如何。我尝试将键更改为 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>
    );
  }
1个回答

1
这里是:

开始

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 }))
  );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接