2017-05-26 72 views
0

無法從陣列中刪除我的名單,我也使用反應更新的插件,但它沒有工作onClick從reactjs中的數組中刪除對象?

我刪除功能

deleteTips(item){ 
    var array = this.state.newTips; 
    var index = array.indexOf(item) 
    array.splice(index, 1); 
    this.setState({newTips: array }); 
    } 

我的渲​​染功能

{ this.state.newTips.map((link, j) => { 
        const nameVal = "tips" + j 
        return(
         <div className="formLabel" key={j}> 
         <div style={{width:"90%","float":"left"}}> 
          <Field 
          type="text" 
          name={nameVal} 
          hintText="Tips" 
          component={TextField} 
          onKeyUp={this.ChangeName.bind(this,j)} 
          fullWidth 
          /> 
         </div> 
         <div style={{width:"8%","float":"right","marginTop":"10px"}}>  
          <img src="../img/cancel.png" style={{marginLeft: '10px'}} onClick={this.deleteTips.bind(this, link)}/> 
         </div> 
         </div>                     
        ) 
        }) 
        } 

回答

1

您正在修改作爲組件狀態的數組,因此您的setState可能無法工作,因爲新狀態與舊狀態相同。

你能嘗試

deleteTips(item){ 
    var array = this.state.newTips.filter(function(s) { return s != item }); 
    this.setState({newTips: array }); 
} 
+0

刪除從數組最後一個 –