我有以下控制我的仪表板的简化代码
function App(props){
const [role, setRole] = React.useState("guest");
const [componentDrawerRender, setComponentDrawerRender] = React.useState(null);
const handleSelectionDrawerClick = (component) => {
setComponentDrawerRender(component);
handleOpenComponentDrawer(true);
};
const handleLoginCallback = (user) => {
if (user !== false) {
handleCloseComponentDrawer();
setRole(user.type); <-- setting the new state does not work
console.log(val.type + " -> " + role ); <-- this here shows != values
} else {
//do nothing
}
};
return (
<Button
onClick={() => {
handleSelectionDrawerClick(
<LoginPage callback={handleLoginCallback} />
);
}}
>
LOG IN
</Button>);
}
这段代码的目的是打开一个抽屉(它会这样做),在抽屉中渲染一个组件(它会这样做),并且在用户使用组件登录后关闭抽屉(它会这样做)并更新状态(它几乎做到了)。
问题出现在handleLoginCallback
方法中。好的数据被发回,状态用好的数据更新。然而,只有页面上的一些组件被更新。
功能组件的重新渲染过程如何工作?它只是再次调用该函数还是只是以某种方式重新计算返回值?以下代码不会在重新渲染时重新计算。可以让某些州依赖于其他州吗?
const [mainList, setMainList] = React.useState((role) => {
console.log(role);
if (role === undefined || role === null) {
return GuestListItems(handleSelectionDrawerClick);
} else if (role === "customer") {
return CustomerListItems;
} else {
return OwnerListItems;
}
});
下面是<LoginPage>
调用回调方法的代码。
onSubmit(e) {
e.preventDefault();
this.setState({ isLoading: true });
this.props.login(this.state, this.handleLoadingBar).then((retState) => {
if(retState === null){
this.props.callback(false); <-- here
}else {
this.props.callback(retState); <-- here
}
});
}