2017-05-18 22 views
0

我的代碼由父級(Show)和子級(Editable)組件組成。 父包含一個數組,其中的子元素被push.I附加屏幕截圖爲清晰。JS拼接無法正常工作以移除React組件

enter image description here

我試圖刪除使用拼接一個孩子(一個數組元素)()。我上拼接得到正確的輸出陣列。在屏幕截圖中的示例如果我從數組中刪除「新」,我的數組arr = [dat2,dat3],但在前端最後一個元素被刪除,並顯示dat2,新的方式如下所示。單擊進行更改,根據需要獲取dat2和dat3。我已經使用正確的索引完成拼接但是它似乎不能在UI中正確工作。

請幫忙。我已經試過幾乎所有:(

我只是轉發所需的功能

父代碼:

handleMinus(id,idShow){ 

    this.state.Example=this.props.result.examples 
    this.state.Example.splice(id,1); 
    this.props.result.examples=this.state.Example; 
    this.setState({create:!this.state.create}) 


}; 

    render() { 
    var showExm = this.props.result.examples.map(function(result,index){ 
      console.log("EditableIntents") 
      return <div key={index}><EditableIntents 
            handleMinus={that.handleMinus} 
            result={result} 
            indexEg={index} 
            indexShowInt={that.props.index} 
            editExample={that.editExample}/> 
          </div> 
      }); 
    return({showExm}); 
} 

兒童:

render() { 
    return(
     <div> 
     <TextField 
       defaultValue={this.props.result} 
       hintText={this.props.result} 
       onChange= {this.changeEg} 
       id="editText" 
      /> 
      <span><IconButton id={"aa"+1} onClick={this.handleMinus} iconStyle={{width: 72, height: 72, float: -60}}><span><MinusIcon /> </span></IconButton></span> 
      </div> 
     ) 
    } 

handleMinus(){ 
    console.log(this.props.indexEg); 
    console.log("in Grand child:",this.props.result,this.props.indexEg); 
    this.props.handleMinus(this.props.indexEg,this.props.indexShowInt) 
    } 
+0

您需要爲您的孩子添加獨特和持久的密鑰,以便反應能夠正確協調。 –

+0

當我創建EditableIntents(key = {index})時,我添加了鍵值 – shinite

+0

由於React組件基於純函數,所以不應該使用'splice',因爲它直接改變狀態。相反,使用'slice'並用'setState'方法替換新的切片狀態。 –

回答

0

還有就是用食指問題可能

孩子:

render() { 

    return(
     <div> 
     <TextField 
       defaultValue={this.props.result} 
       hintText={this.props.result} 
       onChange= {this.changeEg} 
       id="editText" 
      /> 

/* I have just changed here your onClick function */ 

      <span><IconButton id={"aa"+1} onClick={() => this.handleMinus(index)} iconStyle={{width: 72, height: 72, float: -60}}><span><MinusIcon /> </span></IconButton></span> 


      </div> 
     ) 

    } 

/*and here I have added parameter */ 

handleMinus(keyid){ 
    console.log(this.props.indexEg); 
    console.log("in Grand child:",this.props.result,this.props.indexEg); 
    this.props.handleMinus(keyid,this.props.indexShowInt) 
    } 

Also you should define "this.state.Example" as array 

handleMinus(id,idShow){ 

this.state.Example = []; 

    this.state.Example=this.props.result.examples 
    this.state.Example.splice(id,1); 
    this.props.result.examples=this.state.Example; 
    this.setState({create:!this.state.create}) 
}; 

它可以幫助你。

+0

我試過了,但它沒有幫助。我得到相同的結果,在用戶界面錯誤的結果。另外通過onClick = {()=> this.handleMinus(index)}你需要onClick = {()=> this.handleMinus(this.props.indexEg)}對嗎? – shinite

+0

是的,它可能會幫助你 –

+0

但我沒有得到正確的結果。 – shinite