我的代码如下:
const ManageModules: React.FC < IProps > = ({
history
}) => {
const [CurrentlyRegisteredModules, setCurrentlyRegisteredModules] = useState(null as unknown as any[])
const [SelectedModule, setSelectedModule] = useState(null as unknown as any);
useEffect(() => {
userModuleService.addUserModule(SelectedModule.id)
.subscribe(res => {
setCurrentlyRegisteredModules(x => {
x.push(new RegisteredModules(res.data));
return x;
});
});
})
},
[SelectedModule]);
useEffect(() => {
console.log('Current Reg Change');
}, [CurrentlyRegisteredModules]);
}
每当SelectedModule发生变化时,监听它的效果就会很好并返回一个值。然后,我使用setCurrentlyRegisteredModules将结果推送到数组CurrentlyRegistered Modules。
然而,我面临的问题是,监听CurrentlyRegisteredModules的效果没有被触发,但当我在控制台中检查CurrentlyRegistered Modules时,它显示结果已添加到区域中。
有人能认出我可能做错了什么吗。
更改以下代码
setCurrentlyRegisteredModules(x => {
x.push(new RegisteredModules(res.data));
return x;
});
至
setCurrentlyRegisteredModules(x => {
let newX = [...x]
newX.push(new RegisteredModules(res.data));
return newX;
});
不要使x
发生突变。