2015-09-06 51 views
0

我正在從here一個反應教程,並試圖添加刪除按鈕來刪除列表上的名稱。但是,如果我在setState方法中設置了friends:this.state.friends.splice(findIndex,1),那麼刪除將無法正常工作,但如果我在setState方法之外設置了this.state.friends.splice(findIndex,1),它將起作用,有人請解釋爲什麼?謝謝(這裏是jsfiddle)。
(編輯:這是從鏈路的JSX)反應setState不能與array.prototype.splice

var HelloHandler = React.createClass({ 
    getInitialState: function(){ 
     return{ 
      name: 'Tyler McGinnis', 
      friends: ['Jake Lingwall', 'Murphy Randall', 'Merrick Christensen'] 
     } 
    }, 
    addFriend: function(friend){ 
     this.setState({ 
      friends: this.state.friends.concat([friend]) 
     }) 
    }, 
    deleteFriend: function(name){ 
     findIndex=this.state.friends.indexOf(name); 
     this.state.friends.splice(findIndex,1)// 
     this.setState({ 
      friends: this.state.friends 
      //delete won't work properly if change to friends:this.state.friends.splice(findIndex,1) 
     }) 
    }, 
    render: function(){ 
     return (
     <div> 
      <div> 
       Hello{this.state.name} 
      </div> 
      <div> 
       <PrintFriends friendList={this.state.friends} deleteFriend={this.deleteFriend}/> 
      </div> 
      <div> 
       <AddFriend addFriend={this.addFriend} /> 
      </div> 
     </div> 
    ) 
    } 
}); 


var AddFriend=React.createClass({ 
    getInitialState: function(){ 
     return { 
      inputName:'' 
     } 
    }, 
    setFriendNameToState: function(evt){ 
     this.setState({ 
      inputName: evt.target.value 
     }) 
    }, 
    updateFriendNameToList: function(){ 
     this.props.addFriend(this.state.inputName); 
     this.setState({ 
      inputName: '' 
     }) 
    }, 
    render: function(){ 
     return(
      <div> 
       <input type='text' onChange={this.setFriendNameToState} /> 
       <button onClick={this.updateFriendNameToList}>update list</button> 
      </div> 
     ) 
    } 
}); 

PrintFriends=React.createClass({ 
    deleteName: function(people){ 
     this.props.deleteFriend(people.name); 
    }, 
    render: function(){ 
       var self=this; 
       nameList=this.props.friendList.map(function(name){ 
           return(
            <li key={name}> 
             {name} <button onClick={this.deleteName.bind(null,{name})}>delete</button> 
            </li> 
           ) 
          }.bind(self)); 
       return(
        <div> 
         <h3> Friends </h3> 
         <ul> 
          {nameList} 
         </ul> 
        </div> 
       ) 
      } 
}) 


React.render(<HelloHandler />, document.getElementById('app')); 
+0

請包括您在問題中討論的實際代碼,而不僅僅是鏈接。僅有鏈接的問題可能會被刪除。 –

+0

我認爲如果我提供jsfiddle,對人來說會更容易 – seanh

+1

@seanh http://i.imgur.com/QOoS04N.gif – Jan

回答