使用setState反应错误

时间:2018-04-08 22:08:41

标签: javascript reactjs

尝试在单个组件上使用setState时出现以下错误。

警告:数组或迭代器中的每个子节点都应该有一个唯一的“键”支柱。

  • 我在州内创建了这个列表。
  • 在按钮上,我想更新列表

我的代码:

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;

2 个答案:

答案 0 :(得分:3)

  

键帮助React识别哪些项目已更改,已添加或已删除。应该给出数组内部元素的键,以赋予元素稳定的标识

https://reactjs.org/docs/lists-and-keys.html#keys

使用key函数

时,必须向呈现的组件添加map()属性
<ul>
    {this.state.sistemas.map(sistema => <li key={sistema.id}>{sistema}</li>)}
</ul>

答案 1 :(得分:1)

使用箭头函数setState然后按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;

Edit 61jqz3yklw