删除React中的项目

时间:2018-06-12 10:08:25

标签: reactjs

嘿,我有一个问题,在反应中删除元素。单击删除按钮后,我在控制台中出错:'script.js:67 Uncaught TypeError:无法在Object上读取未定义的属性'bind'atClick at Object.ReactErrorUtils.invokeGuardedCallback at executeDispatch at Object.executeDispatchesInOrder at executeDispatchesAndRelease at executeDispatchesAndReleaseTopLevel at atAachAccumulated at Object.processEventQueue'的Array.forEach。

        var Movie = React.createClass({
      propTypes: {
        movie: React.PropTypes.object.isRequired,
        remove: React.PropTypes.func.isRequired
      },

      render: function() {
        return (
          React.createElement('li', {key: this.props.movie.id},
            React.createElement(Remove,{remove: this.props.remove, id: this.props.movie.id}),
          )
        )
      }
    });
var MovieElem = React.createClass({
  propTypes: {
    movies: React.PropTypes.array.isRequired
  },

  getInitialState: function() {
    return {
        movies
    };
  },

  deleteMovie: function(id) {
    this.setState({
      movies: this.state.movies.filter(movie => movie.id !== id)
    })
  },

  render: function() {
    return (
      React.createElement('div', {},
        React.createElement('ul', {},
          this.state.movies.map(function(movie) {
            return React.createElement(Movie, {key: movie.id, movie: movie, remove: () => this.deleteMovie.bind(this)});
          })
      )
    )
  }
});

var Remove = React.createClass({
  propTypes: {
    id: React.PropTypes.number.isRequired,
    remove: React.PropTypes.func.isRequired
  },

  render: function() {
    return (
      React.createElement('button', {onClick: () => { this.props.remove(this.props.id) }}, 'Delete')
    )
  }
})

1 个答案:

答案 0 :(得分:1)

您需要绑定map函数才能在其中正确引用this

render: function() {
    return (
      React.createElement('div', {},
        React.createElement('ul', {},
          this.state.movies.map(function(movie) {
            return React.createElement(Movie, {key: movie.id, movie: movie, remove: this.deleteMovie});
          }.bind(this))
      )
    )
  }