簡體   English   中英

React.JS:動態添加和刪除字段

[英]React.JS: Add and Remove field dynamically

我的 state 中有:

this.state = { inputs: ['0'] } 

在我的渲染中:

   {this.state.inputs.map((input, i) =>     <Travel formName={FORM_NAME} number={input}/>)}
    <button onClick={ () => this.appendInput() }> CLICK ME TO ADD AN INPUT   </button>
    <button onClick={ () => this.deleteInput() }>  Delete   </button>

現在,當我單擊this.appendInput()時,我添加了一個如下字段:

  appendInput() {
    var newInput = `${this.state.inputs.length}`;
    console.log("`${this.state.inputs.length}`" , `${this.state.inputs.length}`)
    this.setState(prevState => ({ inputs: prevState.inputs.concat([newInput]) }));
    console.log("this.state.inputs add ", this.state.inputs)
    this.forceUpdate();
}

但我不明白如何處理deleteInput ,如何以這種方式刪除最后一個字段?

編輯:我試過這樣:

deleteInput(){
  var newInput = this.state.inputs.pop();
  this.setState( ({ inputs: newInput }));
  this.forceUpdate();
}

但后來我收到消息:

_this.state.inputs.map

像這樣寫你的刪除 function ,你從數組中分配彈出數據。

deleteInput(){
  var newInput = [...this.state.inputs];
  newInput.pop();
  this.setState( ({ inputs: newInput }));
  this.forceUpdate();
}

pop()將返回已刪除的元素,您不想將 state 設置為。 這樣做會將您的 state 設置為剛剛刪除的單個元素。 這就是導致您的錯誤的原因,因為您嘗試在不是列表的 object 上調用map()

相反,您的deleteInput()應該這樣做:

this.setState(state => state.inputs.slice(0,-1))

這將從 state 中正確刪除輸入數組的最后一個元素。

此外,作為旁注,調用setState()會自動對重新渲染進行排隊,因此調用this.forceUpdate()是不必要且低效的。

您應該能夠使用.pop()刪除輸入數組中的最后一項

這個線程有一些關於popslice的更詳細的答案: Remove last item from array

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM