状态变量在功能组件中有错误的值

state variable has wrong value in functional component

我正在尝试在表单中添加和删除输入框。我将使用 useState 挂钩控制此框。我对添加状态变量没有任何问题,但是当我想从状态变量中删除时,状态变量有错误的值。

import React, { useState } from 'react';
export default function Addable() {
  const [element, setElement] = useState([]);
  function add() {
    const list = [...element];
    const length = element.length;
    list.push(
      <React.Fragment>
        <input key={length} />
        <button onClick={()=>{_delete(length)}}>delete</button>
      </React.Fragment>,
    );
    setElement(list);
  }
  function _delete(index) {
    //****element has wrong value here****//
    const list = [...element];
    list.splice(index, 1);
    setElement(list);
  }
  return (
    <React.Fragment>
      <button onClick={add}>add Element</button>
      {element}
    </React.Fragment>
  );
}

The slice function不会改变list数组

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
animals.slice(2)
console.log(animals);

您可能想使用 splice instead, to prevent closure problem, pass a function to settlement to set the state on the current state

function _delete(index) {
    //****element has wrong value here****//
    console.log(element);
    setElement((currentEl) => {
      const list = [...currentEl];
      list.splice(index, 1);
      return list
    });
  }

注意:如果使用不受控的输入组件,需要为输入生成一个唯一的id,并设置为key。因为 React 将检查 key 以了解要删除哪个元素。例如,你有一个元素的长度为 5,然后你删除元素索引 2 所以现在元素的长度为 4 但索引 2 仍然存在,所以 React 不知道你删除了索引 2(因为键 2 仍然存在)所以它会将 3 移到 2,4 移到 3.. Check this for a better explanation and demo

您需要创建一个唯一的id,uuid as a choice

function add() {
    const list = [...element];
    const length = element.length;
    const uniqueId = uuid()
    list.push(
     {id: uniqueId
      comp: () => (<React.Fragment>
        <input key={uniqueId} />
        // index is length-1
        <button onClick={()=>{_delete(uniqueId)}}>delete</button>
      </React.Fragment>)
     }
    );
    setElement(list);
  }

function _delete(elementId) {
   // Because we set new state on current state
   // it's better to pass an function into setElement like this to prevent some problem with closure
   setElement(currently =>{
      return currently.filter(el => el.id !== elementId );
    });
}
return (
  <React.Fragment>
    <button onClick={add}>add Element</button>
    {element.map(el => el.comp())}
  </React.Fragment>
);