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

时间:2020-07-15 11:27:18

标签: reactjs react-hooks react-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>
  );
}

1 个答案:

答案 0 :(得分:4)

The slice function不会更改list数组

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

您可能想使用splice来防止闭合问题,请传递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,并将其设置为键。因为React将检查密钥以知道要删除哪个元素。例如,您的元素的长度为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>
);

Edit hidden-currying-hmh4m