反应处理事件

时间:2017-08-22 16:07:11

标签: javascript reactjs

简单的待办事项清单。我想添加一个删除功能,但收到错误:

  

proxyConsole.js:56警告:setState(...):无法在现有状态转换期间更新(例如在render或其他组件的构造函数中)。渲染方法应该是道具和状态的纯函数;构造函数副作用是反模式,但可以移动到componentWillMount

当我试图掌握它时,我可能会尝试使用绑定。

class App extends Component {
  constructor(props) {
    super(props);
     this.onDelete = this.onDelete.bind(this);
     this.state = {
     todos: ['wash up', 'eat some cheese', 'take a nap'],
  };
}

render() {
  var todos = this.state.todos;
  todos = todos.map(function(item, index){
   return(
     <TodoItem item={item} key={index} onDelete={this.onDelete}/>
  )
}.bind(this));

return (
  <div className="App">
    <ul>
      {todos}
    </ul>
  </div>
);
}

onDelete(item){
    var updatedTodos = this.state.todos.filter(function(val, index){
      return item !== val;
    });
    this.setState({
      todos:updatedTodos
    });
  }
}

class TodoItem extends Component {
  constructor(props) {
    super(props);
    this.handleDelete = this.handleDelete(this);

  }

  render(){
    return(
      <li>
        <div className="todo-item">
          <span className="item-name">{this.props.item}</span>
          <span className="item-delete" onClick={this.handleDelete}> x</span>
        </div>
      </li>
    );
  }

handleDelete(){
    this.props.onDelete(this.props.item);
  }
}

1 个答案:

答案 0 :(得分:2)

  

我认为你在child组件的构造函数中调用handleDelete处理程序。它应该是:

this.handleDelete = this.handleDelete.bind(this);

class App extends React.Component {
  constructor(props) {
    super(props);
    this.onDelete = this.onDelete.bind(this);
    this.state = {
      todos: ["wash up", "eat some cheese", "take a nap"]
    };
  }

  render() {
    var todos = this.state.todos;
    todos = todos.map(
      function(item, index) {
        return <TodoItem item={item} key={index} onDelete={this.onDelete} />;
      }.bind(this)
    );

    return (
      <div className="App">
        <ul>
          {todos}
        </ul>
      </div>
    );
  }

  onDelete(item) {
    var updatedTodos = this.state.todos.filter(function(val, index) {
      return item !== val;
    });
    this.setState({
      todos: updatedTodos
    });
  }
}

class TodoItem extends React.Component {
  constructor(props) {
    super(props);
    this.handleDelete = this.handleDelete.bind(this);
  }

  render() {
    return (
      <li>
        <div className="todo-item">
          <span className="item-name">{this.props.item}</span>
          <span className="item-delete" onClick={this.handleDelete}> x</span>
        </div>
      </li>
    );
  }

  handleDelete() {
    this.props.onDelete(this.props.item);
  }
}

ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"/>