![](/img/trans.png)
[英]React redux - parent state changing, but child components not re-rendering
[英]Child Components not re-rendering despite a state-change in Parent
我有一个组件Shipping
,它有多个状态变量,其中一个是一个名为count
的对象。
// Example of count content:
{
"CCI-250S1" : {"count" : 0, "expected" : 3000}
}
父组件Shipping
将count
作为道具传递给子组件:
<InventoryList
items={this.state.items}
isChecking={this.state.isChecking}
count={this.state.count} />
仍然在Shipping
中,有一个带有onClick
功能的按钮:
async handlePartSubmit(event) {
event.preventDefault();
this.setState({'upc' : ''});
let result = await SpireService.getItemByUPC(this.state.upc);
let count = { ...this.state.count};
let entry = count[result.partNo];
let qty = 0;
this.state.items.forEach(value => {
if (value.inventory.partNo === result.partNo) {
qty = value.committedQty;
}
});
if (entry === undefined) {
count[result.partNo] = {
"expected" : Number.parseInt(qty),
"count" : Number.parseInt(result.unitOfMeasures[result.uomCode].quantityFactor)
}
} else {
entry.count += Number.parseInt(result.unitOfMeasures[result.uomCode].quantityFactor);
}
this.setState({'count' : count});
return false;
}
因为我在父组件中调用setState({...})
,根据我对 React 的理解,子组件应该重新渲染,因为状态已经改变,但不会发生重新渲染。
这是子组件,特别是 Icon 不会像count
中的值那样改变。
getIcon(partNo) {
if (this.props.isChecking) {
let entry = this.state.count[partNo];
if (entry === undefined) {
return <td className="check red"><i className="bi bi-x-circle" /></td>;
}
if (entry.count === 0) return <td className="check orange"><i className="bi bi-dash-circle" /></td>
if (entry.count === entry.expected) return <td className="check green"><i className="bi bi-check-circle" /></td>
return <td className="check red"><i className="bi bi-x-circle" /></td>
} else return "";
}
populateItemList() {
return this.props.items.map((item) =>
<tr key={item.id}>
<td>
{item.partNo}
</td>
<td>
{item.orderQty}
</td>
<td>
{item.backorderQty}
</td>
<td>
{item.committedQty}
</td>
{this.getIcon(item.partNo)}
</tr>
);
}
// RENDER child component
render() {
return (
<Table bordered hover>
<thead>
<tr>
<th>Part No.</th>
<th>Order Qty.</th>
<th>Backordered Qty.</th>
<th>To Ship</th>
{this.props.isChecking &&
<th>Checked</th>
}
</tr>
</thead>
<tbody>
{this.populateItemList()}
</tbody>
</Table>
);
}
所以我的问题是为什么当count
状态改变时子组件不会重新渲染?
populateItemList() {
return this.props.items.map((item) =>
应该:
populateItemList() {
return this.state.items.map((item) =>
通过确保我在getIcon()
中读取this.props.count
而不是this.state.count
,我能够正确更新内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.