【发布时间】:2021-05-05 11:36:21
【问题描述】:
我正在使用 react-redux 来管理状态和 axios 来进行 API 调用。
我的默认状态:
const defaultState = {
isLoading: true,
isAuthenticated: false,
authUser: {}
}
一旦 API 的登录调用成功运行,isLoading 和 authUser 都会更新。这里没有错。
在 userProfile 组件中,我使用以下内容从商店获取登录用户的 ID:
const authUser = useSelector(state => state.authentication.authUser);
const user = users.getUser(authUser.id);
console.log(authUser);
authUser 在页面加载时始终为空,但迟了一秒,它再次打印,这次是状态内容。
我在自定义 PrivateRoute 组件后面有 userProfile 组件:
const PrivateRoute = ({ component: Component, ...rest }) => {
const authentication = useSelector(state => state.authentication);
return (
<Route
{...rest}
render={props =>
authentication.isAuthenticated ? (
<Component {...props} />
) : (
authentication.isLoading ? 'loading...' :
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
}
/>
)
};
loading... 文本在组件赶上之前显示,然后 2 个控制台日志一个接一个地出现。第一个为空,第二个为数据。
我在这里缺少什么?这种异步的东西快把我逼疯了!
【问题讨论】:
标签: reactjs async-await react-redux