import React, {useState} from "react";
const App = () => {
const cities = [
{id: 1, name: 'Moscow'},
{id: 2, name: 'Kazan'},
{id: 3, name: 'Sochi'},
{id: 4, name: 'Ekaterinburg'}
]
const [data, changeData] = useState(cities);
const handler = () => {
console.log(data);
data.push({
id: 5, name: 'Saint-Petersburg'
});
changeData(
data
);
console.log(data);
}
console.log('render');
return (
<div>
<button onClick={() => handler()}>Click Me</button>
{
data.map((item) => {
return (
<ul key={item.id}>
<li>{item.name}</li>
</ul>
)
})
}
</div>
);
};
export default App;
Что в данном примере я сделал не правильно?
import React, { useState } from "react";
const initialState = [
{ id: 1, name: 'Moscow' },
{ id: 2, name: 'Kazan' },
{ id: 3, name: 'Sochi' },
{ id: 4, name: 'Ekaterinburg' },
];
const App = () => {
const [ cities, setCities ] = useState(initialState);
const handler = () => {
setCities(prevState => [...prevState, { id: 5, name: 'Saint-Petersburg' }]);
};
return (
<div>
<button onClick={handler}>Click Me</button>
<ul>
{cities.map(city => <li key={city.id}>{city.name}</li>)}
</ul>
</div>
);
};
export default App;
data.push({ id: 5, name: 'Saint-Petersburg' });
changeData( data );