简体   繁体   English

在 React 中使用 Splice 修改 Hook setState

[英]Modifying Hook setState for an Array in React using Splice

I'm trying to splice an array hook State, so I can remove items from my list.我正在尝试拼接一个数组挂钩 State,这样我就可以从我的列表中删除项目。 I know you're not supposed to modify any hook states directly, so I made a copy into array2 before settting it, but it's removing all items below the one I click, instead of just the one I click.我知道您不应该直接修改任何钩子状态,因此我在设置之前将其复制到 array2 中,但它会删除我单击的项下方的所有项目,而不仅仅是我单击的项目。 Any ideas?有任何想法吗?

export default function Shopping() {
  const [item, setItem] = useState('Default');
  const [list, setList] = useState([]);
  const [array, setArray] = useState([]);

  let array2 = [];
  const name = ({ target }) => setItem(target.value);

  const remove = ({ target }) => {
    for (let x = 0; x <= array.length; x++) {
      if (array[x] === target.value) {
        array2 = list;
        array2 = array2.splice(x, 1);
      }
      setList([...list, array2]);
    }
  };

  const create = () => {
    if (item !== 'Default' && document.getElementById('box').value !== '') {
      let value = document.getElementById('box').value;

      setArray([...array, value]);

      setList([
        ...list,
        <div>
          <p>
            {' '}
            {item} &nbsp;&nbsp;&nbsp;&nbsp; Qty: 1<button>+</button>
            <button>-</button>
            <button
              value={document.getElementById('box').value}
              onClick={remove}
            >
              x
            </button>
          </p>
        </div>,
      ]);
    } else {
      alert('Please enter an Item');
    }

    document.getElementById('box').value = '';
    setItem('Default');
  };

  const clear = () => setList([]);

  return (
    <div>
      <input type='textbox' id='box' onChange={name} />
      <input type='button' value='Add' onClick={create} />
      <input type='button' value='Clear' onClick={clear} />

      {list}
    </div>
  );
}

You should just store the strings in the list array and display the elements using a map function:您应该只将字符串存储在list数组中并使用map function 显示元素:

export default function Shopping() {
  const [item, setItem] = useState('Default');
  const [list, setList] = useState([]);

  const name = ({ target }) => setItem(target.value);

  const remove = (index) => {
    const filteredList = [...list].splice(index, 1);
    setList(filteredList);
  };

  const create = () => {
    if (item !== 'Default' && item !== '') {
      setList([...list, item]);
    } else {
      alert('Please enter an Item');
    }

    setItem('Default');
  };

  const clear = () => setList([]);

  return (
    <div>
      <input type='textbox' id='box' onChange={name} />
      <input type='button' value='Add' onClick={() => create()} />
      <input type='button' value='Clear' onClick={() => clear()} />

      {list.map((it, index) => {
        return (
          <div key={index}>
            <p>
              {' '}
              {it} &nbsp;&nbsp;&nbsp;&nbsp; Qty: 1<button>+</button>
              <button>-</button>
              <button value={it} onClick={() => remove(index)}>
                x
              </button>
            </p>
          </div>
        );
      })}
    </div>
  );
}
```

Just Update the code in remove function because array2 = list also copies the reference of list array so when you update the array2 it also update the list array.so replace the remove function code with given code below.只需更新删除 function 中的代码,因为array2 = list还复制列表数组的引用,因此当您更新 array2 时,它也会更新列表数组。因此,将删除 function 代码替换为下面的代码。

if ((array[x])===target.value){
array2 = list.map(item=>item)
array2 = array2.splice(x,1)
}

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

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