如何在React挂钩中正确更新状态

时间:2020-10-16 20:04:38

标签: javascript reactjs typescript react-native

因此,问题在于,每当我按下删除按钮时,它都将删除删除操作,最后删除的输入和按钮与索引无关。我试图将密钥更改为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 个答案:

答案 0 :(得分:1)

在这里:

<link>

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

href