我有一个由地图渲染的列表组件,这就是我在反应函数组件中定义数据的方式:
const [projMap, setProjMap] = useState<Map<number, FolderModel>>(new Map<number, FolderModel>());
当我在 React 函数组件中设置地图时,如下所示:
React.useEffect(() => {
if (folderProjList && folderProjList.length > 0) {
if (currFolder) {
let cachedExpand = projMap.get(currFolder.id)?.expand;
let folderModel: FolderModel = {
expand: cachedExpand ? cachedExpand : true,
projects: folderProjList
};
projMap.set(currFolder.id, folderModel);
setProjMap(projMap);
}
}
}, [folderProjList]);
使用projMap渲染UI时没有触发重新渲染。然后我改变风格是这样的:
React.useEffect(() => {
if (folderProjList && folderProjList.length > 0) {
if (currFolder) {
setProjMap((prevMapState) => {
const newMapState = new Map<number, FolderModel>(prevMapState);
let cachedExpand = newMapState.get(currFolder.id)?.expand;
let folderModel: FolderModel = {
expand: cachedExpand ? cachedExpand : true,
projects: folderProjList
};
newMapState.set(currFolder.id, folderModel);
return newMapState;
});
}
}
}, [folderProjList]);
重新渲染效果很好。用户界面始终保持最新。这两种setState有什么不同?为什么第二种风格可以立即重新渲染,而第一种风格却不能?