Reputation: 797
I'm getting the following error when trying to use setState on a single component.
Warning: Each child in an array or iterator should have a unique "key" prop.
my code:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props)
this.state = { sistemas: [] };
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
console.log('Indo buscar dados');
this.setState({
sistemas: [
{ id: '1', nome: 'sistema1' },
{ id: '2', nome: 'sistema2' },
{ id: '3', nome: 'sistema3' }
]
})
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<button className='button' onClick={this.handleClick}>
Click Me
</button>
<p>{this.state.sistemas}</p>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<div>
<ul>
{this.state.sistemas.map(sistema => <li>{sistema}</li>)}
</ul>
</div>
</div>
);
}
}
export default App;
Upvotes: 2
Views: 39
Reputation: 2227
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity
https://reactjs.org/docs/lists-and-keys.html#keys
You have to add key
attribute to rendered components when using map()
function
<ul>
{this.state.sistemas.map(sistema => <li key={sistema.id}>{sistema}</li>)}
</ul>
Upvotes: 3
Reputation: 6743
use Arrow function to setState then map the data by the id
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props)
this.state = { sistemas: [] };
this.handleClick = this.handleClick.bind(this)
}
handleClick = () => {
console.log('Indo buscar dados');
this.setState({
sistemas: [
{ id: '1', nome: 'sistema1' },
{ id: '2', nome: 'sistema2' },
{ id: '3', nome: 'sistema3' }
]
})
}
render() {
console.log(this.state.sistemas, 'check this')
return (
<div className="App">
<button className='button' onClick={this.handleClick}>
Click Me
</button>
<div>
<ul>
{this.state.sistemas.map(sistema =>
<li key={sistema.id}>{sistema.nome}</li>
)}
</ul>
</div>
</div>
);
}
}
export default App;
Upvotes: 1