reactjs - 使用 redux 反应受保护的路由
问题描述
我创建了一个单独node.js
restful API
的用于检查用户令牌是否有效。我为我的反应保护路线做了这个,即使我的大部分人endpoints
已经检查了用户令牌。
我的 redux Thunk:
const verifyToken = () => {
return async (dispatch: Dispatch) => {
await axios
.get("http://localhost:9999/authenticate", {
headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
})
.then(async (resp) => {
const { message } = await resp.data;
console.log(message);
if (message === "verified") dispatch({ type: "signIn-success" });
})
.catch((err) => {
console.log(err);
dispatch({ type: "logout-user" });
});
};
};
受保护的路线:
const ProtectedRoute: FC<{ children: ReactNode; path: string }> = ({
children,
path,
}) => {
const dispatch = useDispatch();
dispatch(verifyToken()); //dispatch thunk
const status = useSelector((store: RootStore) => store.status)
return status && status === "loggedOut" ? (
<Redirect to="/" />
) : (
<Route path={path} render={() => <>{children}</>} />
);
};
问题是dispatch
我的 thunk 需要时间,因此"/"
即使用户令牌检查尚未完成,它也会重定向到。
所以会发生什么,状态的值"loggedOut"
首先是然后我的 thunk 将检查令牌是否有效。如果是,状态变为"loggedIn"
,但为时已晚,因为它已经重定向到"/"
解决方案
您需要在调度操作时加载,如下所示:
const ProtectedRoute: FC<{ children: ReactNode, path: string }> = ({
children,
path,
}) => {
const [loading, setLoading] = useState(true);
const dispatch = useDispatch();
const status = useSelector((store: RootStore) => store.status);
async function verify() {
await dispatch(verifyToken()); //dispatch thunk
setLoading(false);
}
useEffect(() => {
verify();
}, []);
if (loading) return <div>Show Loading...</div>;
return status === "loggedOut" ? (
<Redirect to="/" />
) : (
<Route path={path} render={() => <>{children}</>} />
);
};
推荐阅读
- javascript - 如何将html表转换为引导表?
- bash - 如何将包含``的命令分配给bash shell脚本中的变量?
- java - Android 创建视图崩溃
- postman - Postman 脚本:是否可以在不同的环境中设置变量?
- python - 如何在 ABAQUS UMAT 子程序中调用 Python
- strapi - 如何在strapi的注册API中上传图像?
- html - 是否可以仅设置不透明度
但不是元素?
- javascript - 我应该如何使用 webpack DefinePlugin 访问 index.ejs 中的哈希包文件名
- java - oracle.AQ.AQOracleSQLException:无效的列类型
- python - 如何用Python中字典中的键替换列表中的项目