问答详情
源自:2-3 实现列表项的删除功能

我就想知道为啥跑不起来,在点击add的时候总是报错,错误信息如下,求解答

import React from 'react';


class TodoList extends React.Component {

  constructor(props){

    super(props);

    this.state = {

      list: [],

      inputValue: ''

    }

    this.handleBtnClick = this.handleBtnClick.bind(this);

    this.handleInput = this.handleInput.bind(this);

    this.handleItemClick = this.handleItemClick.bind(this);

  }

  handleInput(e){

    this.setState({

      inputValue: e.target.value

    })

  }

  handleBtnClick(){

    this.setState({

      list: [...this.state.list, this.state.inputValue],

      inputValue: ''

    })

  }

 

  handleItemClick(index){

    const list = [...this.state.list];

    list.splice(index, 1);

    this.setState({list});

  }


  render() {

    return (

      <div>

        <div>

          <input value={this.state.inputValue} onChange={this.handleInput}/>

          <button onClick={this.handleBtnClick}>add</button>

        </div>

        <ul>

          {

            this.state.list.map((item, index) => {

              return (

               <li key={index} onClick={this.handleItemClick(index)}>{item}</li>

              )

            })

          }

        </ul>

      </div>

    );

  }

}


export default TodoList;


报错信息:Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.


提问者:慕婉清2499770 2019-03-21 23:53

个回答

  • 知晓同丶
    2019-03-22 15:56:04
    已采纳

    onClick={this.handleItemClick(index)} 改成 onClick={() => this.handleItemClick(index)}