如何从React中的数组状态中删除元素?

时间:2017-03-07 02:14:40

标签: javascript reactjs firebase firebase-realtime-database

我在firebase中有一个数组,其根分支名为Rooms,应用程序中的状态名为rooms(数组)。当用户输入新房间名称并按提交时,我能够将其添加到Rooms对象的末尾。

screenshot of firebase database

我想实现一个删除方法,所以当用户点击房间名称旁边的x按钮时,它会从状态和firebase中删除该元素,但我没有成功实现它。

我的起点是来自SO similarly titled的帖子。我无法在有效的<li>组件上实现代码。这就是我所拥有的:

Chatroom.js

  handleRemove(index) {
    var array =  this.state.rooms.slice();
    array.splice(index, 1);
    this.setState({
      rooms: array
    })
  }
  ...
  render(){
    <div><DisplayChatrooms rooms={this.state.rooms} handleRemove={this.handleRemove.bind(this)} /></div>

DisplayChatrooms.js

class DisplayChatrooms extends React.Component{
  render(){
    console.log('handleRemove: ', this.props.handleRemove); //this prints out the handleRemove function just fine
    var rooms = this.props.rooms.map(function(room, index){
      return (
        <li key={index}>{room} <a href="#">x</a></li>
      )
    })
    return(
      <div>
        <ul>
          {rooms}
        </ul>
      </div>

当我修改li以包含handleRemove时,会显示以下错误:Uncaught TypeError: Cannot read property 'props' of undefined

<li key={index}>{room} <a href="#" onClick={this.props.handleRemove}>x</a></li>

如何实现允许用户在单击x时删除该元素的方法?

1 个答案:

答案 0 :(得分:1)

 this.props.rooms.map(function(room, index){
  return (
    <li key={index}>{room} <a href="#">x</a></li>
  )
})

“li”在function(room, index)的范围内,this指向此案例window对象的全局,这就是为什么道具不在this上,你可以使用es6 fat arrow

this.props.rooms.map((room, index) => {})

或老派方法

var self = this;
this.props.rooms.map(function() { self.props.handleRemove })