简体   繁体   English

如何使用钩子从传递键的数组中删除元素?

[英]How to remove an element from an array passing the key using hooks?

I have a simple array like this我有一个像这样的简单数组

let myArray = ['one', 'two', 'three'];

let's say I want to remove the second element, what I would do is假设我想删除第二个元素,我会做的是

myArray.splice(1, 1);

but what if to set this array I am using a hook like this?但是如果我使用这样的钩子来设置这个数组呢?

const [myArray, setMyArray] = useState([]);

what is the correct way to remove an element passing its index and possibly reorder all the indexes in order not to have gaps?删除传递其索引的元素并可能重新排序所有索引以免出现间隙的正确方法是什么?

In React, you do not mutate existing state using methods like .splice .在 React 中,您不会使用.splice等方法改变现有状态。 Instead you will create a new state and pass it to setMyArray .相反,您将创建一个状态并将其传递给setMyArray As an example use, this component will loop over myArray and create a clickable remove button for each element in the array -作为示例使用,该组件将遍历myArray并为数组中的每个元素创建一个可点击的删除按钮 -

 function immutableSplice(arr, index, count) { return [ // return *new* array...arr.slice(0, index), // does not mutate arr...arr.slice(index + count) // does not mutate arr ] } function MyComponent(props) { const [myArray, setMyArray] = React.useState(["", "", ""]); const removeElement = index => event => setMyArray(immutableSplice(myArray, index, 1)) return myArray.map((v, index) => <button key={index} onClick={removeElement(index)}>remove {v}</button> ) } ReactDOM.render(<MyComponent/>, document.body)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>

Immutable state is a principle discipline of the React pattern.不可变状态是 React 模式的原则原则。 Because of this, many libraries exist to help with immutable manipulation of objects and arrays.因此,存在许多库来帮助对对象和数组进行不可变操作。 See Immutable.js and Immer, to name a few.请参阅 Immutable.js 和 Immer,仅举几例。

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

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