简体   繁体   English

this.state.something发生变化并引起了问题

[英]this.state.something mutated and caused issue

For some reason I can't do this 由于某些原因,我无法执行此操作

this.state.something.map(obj => obj.id)

because it caused extra rerendering. 因为它导致了额外的渲染。 How to get something from state, without assign it to a new variable? 如何从状态中获取某些信息,而不将其分配给新变量?

I used to do this ugly hack 我曾经做过这个丑陋的骇客

something_state_holder = this.state.something
something_state_holder.map(obj => obj.id)

but is there any better / more elegant way? 但是有什么更好/更优雅的方法吗?

As @mayank-shukla said, what you are doing here is perfectly valid. 正如@ mayank-shukla所说,您在这里所做的事情是完全正确的。 The map() method iterates through an array and returns and array, but without mutating the iterated one. map()方法遍历一个数组,然后返回和数组,但不更改迭代的数组。 Here's what the MDN documentation says: 这是MDN文档所说的:

The map() method creates a new array with the results of calling a provided function on every element in this array. map()方法创建一个新数组,并对该数组中的每个元素调用提供的函数。

map does not mutate the array on which it is called (although callback, if invoked, may do so). map不会使在其上被调用的数组发生变化(尽管如果调用了回调,则可能会这样做)。

However, should you want to make a shallow copy on an array, you could use slice: 但是,如果要在数组上进行浅表复制,则可以使用slice:

something_state_holder = this.state.something.slice();
var resulting_array = something_state_holder.map(obj => obj.id);

This iterates through the copy, and not the state. 这会遍历副本,而不是状态。 What you did is not creating an array, you are simply assigning the reference to the same array to a new variable. 您所做的不是创建数组,您只是将对同一数组的引用分配给新变量。 So mutating that will mutate the state. 因此,变异会改变状态。

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

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