【问题标题】:How to remove an element from array state in React?如何从 React 中的数组状态中删除元素?
【发布时间】:2017-03-07 02:14:39
【问题描述】:

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

我想实现一个删除方法,所以当用户点击房间名称旁边的 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 时删除该元素的方法?

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database


    【解决方案1】:
     this.props.rooms.map(function(room, index){
      return (
        <li key={index}>{room} <a href="#">x</a></li>
      )
    })
    

    “li”在function(room, index)的范围内,this在这种情况下指向全局window对象,这就是为什么props不在this上,你可以使用es6胖箭头

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

    还是老派的方法

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

    【讨论】:

      猜你喜欢
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多