class App extends React.Component {
state = {
tasks: [
{
id: 1,
title: 'title',
description: 'description',
},
],
}
createTask = () => {
this.setState(({ tasks }) => ({
tasks: [
...tasks,
{
id: 1 + Math.max(0, ...tasks.map(n => n.id)),
title: 'title',
description: 'description',
},
],
}));
}
render() {
return (
<div>
<button onClick={this.createTask}>Добавить задачу</button>
<ul>
{this.state.tasks.map(({ id, title, description }) => (
<li key={id}>id: {id} | {title} | {description}</li>
))}
</ul>
</div>
);
}
}
Что бы Вы изменили в коде?
const uid = () => Math.random().toString(36).slice(2);
class App extends React.Component {
state = {
tasks: [
{
id: uid(),
title: 'title',
description: 'description',
}
]
};
handleCreateTaskClick = () => {
this.setState(state => ({
tasks: [
...state.tasks,
{
id: uid(),
title: 'title',
description: 'description',
},
],
}));
};
render() {
const { tasks } = this.state;
return (
<div>
<button onClick={this.handleCreateTaskClick}>Добавить задачу</button>
<ul>
{tasks.map(task => (
<li key={task.id}>
id: {task.id} | {task.title} | {task.description}
</li>
))}
</ul>
</div>
);
}
}