2017-03-07 1461 views
1

我有一個名爲Rooms的根分支與firebase中的數組,以及名爲rooms(數組)的應用中的狀態。當用戶輸入新房間名稱並按下提交時,我能夠使它成爲這樣,它被添加到Rooms對象的末尾。如何從React中的數組狀態中刪除元素?

screenshot of firebase database

我想實現一個刪除方法,所以當旁邊的房間名稱x按鈕用戶點擊,它就會從國家和火力刪除元素,但我沒有成功實現它。

我的起點是從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
this.props.rooms.map(function(room, index){ 
    return (
    <li key={index}>{room} <a href="#">x</a></li> 
) 
}) 

「麗」是的function(room, index)的範圍,本this被點到全球在這種情況下window對象,這就是爲什麼道具是不是this,您可以使用ES6脂肪箭頭

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

或老派方法

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