[英]ReactJs: Input value doesn't change because due to using Array.map
這是表體:
<tbody>
{this.state.composantInformation.map(composantInformation => {
return (
<tr key={composantInformation.id.toString()}>
<td>{composantInformation.nom_composant}</td>
<td>{composantInformation.categorie}</td>
<td>{composantInformation.description}</td>
<td>{composantInformation.ref}</td>
<td>
<NumericInput
min={0}
max={100}
value={composantInformation.qte}
onChange={this.onQuantiteChange}
/>
</td>
</tr>
);
})}
</tbody>;
這是狀態:
this.state = {
produitInformation: [],
composantInformation: [],
produitId: 0,
produitQte: 0
};
這是發出后端 API 請求的地方:
componentDidMount() {
getProduitDataFromDB()
.then(result => {
this.setState({
produitInformation: result.data
});
})
.catch(error => console.error("(1) Outside error:", error));
}
在最后一列中,當我單擊 Increment/Decrement 時,該值會增加,然后又回到 0。
我相信這與我使用map
來顯示表格數據有關。
{
this.state.produitInformation.map(produitInformation => {
return (
<tr
key={produitInformation.id.toString()}
produitid={produitInformation.id.toString()}
onClick={this.onTableRowClick}
>
<td>{produitInformation.nom_produit}</td>
<td>{produitInformation.prix}</td>
<td>{produitInformation.categorie}</td>
<td>{produitInformation.description}</td>
<td>
<NumericInput
min={0}
max={100}
value={produitInformation.qte}
tablerow={5}
onChange={this.onQuantiteChange}
/>
</td>
</tr>
);
});
}
由於NumericInput
的value
不直接與狀態值相關聯。 知道如何解決這個問題嗎?
您需要更新發生增加的特定數組元素,因此需要兩個參數,一個使用 id 標識元素,另一個是 value
onQuantiteChange(id, value){
const newData = this.state.produitInformation.map(d => {
if(d.id === id) {
return {...d, qte: value}
}
return d;
})
this.setState({produitInformation: newData})
}
也變
<td>
<NumericInput
min={0}
max={100}
value={produitInformation.qte}
tablerow={5}
onChange={(val) => this.onQuantiteChange(produitInformation.id, val)}
/>
</td>
您需要為該 NumericInput 上的 NumericInput 值和 onChange 設置狀態,您需要設置新狀態以便值更改
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.