简体   繁体   中英

Array.concat() returns an empty array

I'm creating a web application using React 16.10 and when I try adding an element to an empty array using Array.concat() , at first it returns an empty array and after the second try it returns the extended array.

The reasons why I'm not using Array.push() :

Here is the code:

const [pizzas, setPizzas]= useState([]);

const addPizza = (type, size, dough, price) => {
    setPizzas(pizzas.concat([{type, size, dough, price}]));
    console.log(pizzas);
}

The addPizza function is triggered when the button is clicked. When I click it the first time, console returns [] , but when I click it the second time, it returns the extended array: [{...}] .

The weird thing is that when I try doing something similar in the browser's console, it works correctly:

const a = [];

a.concat({name: 'James'}); // returns [{name: 'James'}]

.concat() doesn't modify an Array ; it returns a new Array containing the concatenation. Thus, this line does set the pizzas state in the next render to an array with the new item:

setPizzas(pizzas.concat([{type, size, dough, price}]));

...because it sort of translates to this:

const newPizzas = pizzas.concat([{type, size, dough, price}]);
setPizzas(newPizzas);

...but the local pizzas variable you're logging is not modified. The next time useState is called, pizzas will have the new value, however.

setting state in React is asynchronous. When you call a setter obtained from useState the guarantee you have is that in the future the function will be called with the new updated state.

It does not update the existing reference (to pizzas ) - rather it calls the function with the new one.

That's just how state works in react - presumably to create a pretense of immutability inside a render.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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