React中的拼接方法 [英] Splice method in React
问题描述
我正在尝试使用 splice 将新的组件
添加到数组中。如果我使用 concat
所有元素都在最后正确添加,但我还需要使用剪接
。有什么建议吗?
I'm trying to use splice to add new components
into an array. If I use concat
all the elements are added properly at the end, but what I also need is add at the beginning or in the middle of the array using splice
. Any suggest ?
class App extends React.Component {
state = {
components: []
};
addNewElement = (element) => {
this.setState(prevState => ({
//Works fine
//components: prevState.components.concat(element)
components: prevState.components.splice(0, 0, element)
}));
};
}
推荐答案
小心注意改变调用它们的数组的方法和返回调用它们的数组的变异版本的方法之间的区别。
Be careful to note the difference between methods that mutate the array on which they are called and methods which returns mutated versions of the array on which they are called.
prevState.components.splice(0,0,element)
返回一个新数组,其中包含已删除的元素,为了您的目的,这些元素将一无所获。
prevState.components.splice(0, 0, element)
returns a new array containing the elements which have been removed, which for your purposes is going to be nothing.
值得注意的是, splice
也会改变组件数组;改变你的国家元素是一件坏事;避免这种情况的一种简单方法是创建数组的克隆并拼接 。
Notably, splice
also mutates the components array; mutating your State elements is A Bad Thing To Do; one simple way to avoid that is to create a clone of your array and splice that.
this.setState(prevState => {
const components = prevState.components.slice(0);
components.splice(0, 0, element);
return { components };
});
这是功能性的,但相对不优雅。
This is functional, but relatively inelegant.
您可以考虑的其他选择是使用React的不变性助手或使用 slice
将原始数组分成两个,然后 concat
将所有位分开:
Other options you could consider would be to use React's immutability helper or use slice
to divide your original array in two then concat
all the bits together:
const i = // index at which to insert the new elements
const left = prevState.components.slice(0, i)
const right = prevState.components.slice(i)
return {
components: left.concat(elements, right)
}
这篇关于React中的拼接方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!