我有以下代码
父级的相关部分:
const [aggregated] = React.useState(new Map());
let updateAggregate = (month:string, value:number) => {
let init = aggregated.get(month) || 0;
aggregated.set(month, init + value);
};
return (
<AggregateRow classes={classes} resource={resource} aggregated={aggregated} test={changed}/>
)
child :
export interface AggregateRowProps {
classes: Record<"tableCell", string>,
resource: Resource,
aggregated: Map<string, number>,
test: boolean
}
export const AggregateRow = (props: AggregateRowProps) => {
console.log("map", props.aggregated);
return (
<TableRow hover className={props.classes.tableCell}>
{months.map((item, i) => <TableCell key={i}>{props.aggregated.get(item) || 0}</TableCell>)}
</TableRow>
)
};
我想在更新 map (props.aggregated
) 时重新呈现此 TableRow
,我在 console.log
中看到 props.aggregated
正在正确更新,但是 TableRow
从初始渲染开始总是充满 0。
这是因为 props.aggregated 没有被视为已更改,因为它仍然是同一张 map (内部具有不同的值)吗?
最佳答案
当您更新 props.aggregated
时,您是将值附加到当前对象,而不是将新值分配给 props.aggregated
(即创建一个新的 map
).
组件将在其 props 更改时重新渲染,但由于 props.aggregated
是同一个对象,因此不会发生这种情况。
您可以每次都重新创建 Map
而不是附加到它,或者您可以将键值对存储在具有以下类型的简单 object
中:
{ [key: string]: number }
然后不用调用 aggregated.set(key, value)
,您只需创建一个新对象并将新的键值对附加到它:
{
...oldObject,
...{ newKey: (oldObject[newKey] || 0) + newValue },
}
我不会担心这有多高效,因为 React 被设计为以这种方式使用。状态是不可变的,因此创建新状态(而不是改变旧状态)是可行的方法。
这将是一个新的对象引用,因此当新的键值对添加到您的状态时,您的组件将重新呈现。
这是一个例子:
const Parent = () => {
const [aggregated, setAggregated] = useState<{ [key: string]: number }>({})
let updateAggregate = (month: string, value: number) => {
// We set aggregated as a new object, with the new month and value added as a property.
setAggregated(prev => ({
...prev,
...{ month: (prev[month] || 0) + value },
}))
}
return <AggregateRow classes={classes} resource={resource} aggregated={aggregated} test={changed}/>
}
export const AggregateRow = (props: AggregateRowProps) => {
return (
<TableRow hover className={props.classes.tableCell}>
// Access the correct prop using props.aggregated[item]
{months.map((item, i) => <TableCell key={i}>{props.aggregated[item] || 0}</TableCell>)}
</TableRow>
)
};
关于reactjs - 如果 map 值发生变化,如何强制重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60218638/