简体   繁体   English

无法从变异数组渲染元素 - React

[英]Can't render elements from mutated Array - React

So, the problem I've faced is that when I click delete button at any index it just deletes last element for example, if I press first delete button, it should remove first input and the delete button, but what it does is that it deletes last element only... What could be wrong?所以,我面临的问题是,当我在任何索引处单击删除按钮时,它只会删除最后一个元素,例如,如果我按下第一个删除按钮,它应该删除第一个输入和删除按钮,但它的作用是只删除最后一个元素...可能有什么问题?

function App() {
  const [names, setNames] = React.useState([
    "First",
    "Second",
    "third",
    "fourth"
  ]);

  const onChange= (index: number, editedName: string) => {
    const mutatedNames = [...names];
    mutatedNames[index] = editedName;
    setNames(mutatedNames);
  };

  function onDelete(index: number) {
    const nameArr = [...names];
    nameArr.splice(index, 1);
    setNames(nameArr);
  }


  return (
    <div>
      {names.map((name, index) => (
        <ChildComponent
          key={index}
          name={name}
          index={index}
          onChange={onChange}
          onDelete={onDelete}
        />
      ))}
    </div>
  );
}



const Child = React.memo(
  ({ name, index, onChange, onDelete }) => {
    return (
      <div>
        <input
          onChange={(event) => onChange(index, event.target.value)}
        />
        <button onClick={() => onDelete(index)}>delete</button>
      </div>
    );
  }
);

You are using a partially controlled input, this is almost never a good idea.您正在使用部分控制的输入,这几乎不是一个好主意。

Make it fully controlled like so:像这样让它完全控制:

<input
  value={name}
  onChange={(event) => onChange(index, event.target.value)} />

I suggest you read the official guidelines about Forms and Controlled Components and the article about the uncontrolled scenario .我建议您阅读有关 Forms 和Controlled Components的官方指南以及有关非受控场景文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM