我有一个带有useEffect
钩子的功能组件App
,我正在尝试让<Redirect>
子组件在状态更改时重新渲染,特别是对setUserInSystem
的调用,它应该更新userInSystem
,这在渲染方法中明确引用。但是,当userInSystem
更改时,该组件不会重新渲染,我不知道为什么。(注意:异步函数getUserInfo
和getUserByWorkEmail
都按预期工作并检索正确的数据。
const App = (props) => {
const { authState, authData } = props;
const [signedIn, setSignedIn] = useState(false);
const [userInfo, setUserInfo] = useState(undefined);
const [userInSystem, setUserInSystem] = useState(false);
useEffect(() => {
setSignedIn(!(authState !== 'signedIn'));
const fetchUser = async () => {
const data = await getUserInfo();
const userFound = await getUserByWorkEmail(data);
setUserInSystem(userFound);
setUserInfo(data);
};
if (authState === 'signedIn') {
fetchUser();
}
}, [authState]);
return (
<div>
<BrowserRouter>
<Switch>
<Redirect
exact={true}
path="/"
to={userInSystem ? '/dashboard' : '/unverified'}
/>
</Switch>
</BrowserRouter>
</LayoutProvider>
</div>
);
};
创建一个新的钩子,并使用每次获取都会改变的条件来包络重定向:
const [loading, setLoading] = useState(true);
在抓取集中,解析抓取后加载为 false。
const fetchUser = async () => {
setLoading(true);
const data = await getUserInfo();
const userFound = await getUserByWorkEmail(data);
setUserInSystem(userFound);
setUserInfo(data);
setLoading(false);
};
然后在返回中:
<Switch>
{ !loading ? <Redirect
exact={true}
path="/"
to={userInSystem ? '/dashboard' : '/unverified'}
/>
: <div>Loading....</div>
}
</Switch>
尝试在 useEffect 依赖项数组中添加 userInSystem。
useEffect(() => {
setSignedIn(!(authState !== 'signedIn'));
const fetchUser = async () => {
const data = await getUserInfo();
const userFound = await getUserByWorkEmail(data);
setUserInSystem(userFound);
setUserInfo(data);
};
if (authState === 'signedIn') {
fetchUser();
}
}, [authState, ***userInSystem***]);