问题描述
我有一个名为 withAuth 的包装组件,这里的想法是一个 HOC 包装的组件,用于验证来自 cookie 的令牌,但是当使用 redux 调用操作时,它不会重定向到秘密页面,但是如果我不包装使用 next/router 重定向的秘密页面
import React,{ Component } from "react";
import Router from "next/router";
import { getCookie } from "../utils/cookies";
export default function withAuth(WrappedComponent) {
return class withAuth extends Component {
static async getinitialProps(ctx) {
const token = getCookie("authInfo",ctx.req);
// If user doesn't have a token,redirect away
if (!token) {
if (ctx.res) {
ctx.res.writeHead(302,{
Location: "/login",});
ctx.res.end();
} else {
Router.push("/login");
}
}
// Check if Page has a `getinitialProps`; if so,call it.
const pageProps =
WrappedComponent.getinitialProps &&
(await WrappedComponent.getinitialProps(ctx));
// Return props.
return { ...pageProps,token };
}
render() {
return <WrappedComponent {...this.props} />;
}
};
}
但是当令牌存在时它不会重定向并且屏幕崩溃:
// import { request } from "../../utils/request";
import { error } from "../actions/alert";
import Router from "next/router";
import axios from "axios";
export const authConstants = {
USER_LOGIN: "USER_LOGIN",USER_logoUT: "USER_logoUT",};
export const USER_LOGIN = (email,password) => {
return async (dispatch) => {
try {
const authInfo = await axios.post(
"http://localhost:5000/login",{
email: email,password: password,},{ headers: { Accept: "application/json; charset=UTF-8" },withCredentials: true }
);
dispatch({
type: authConstants.USER_LOGIN,authInfo: authInfo.data,});
Router.push("/secret");
} catch (err) {
dispatch(error("User or Password is invalid!"));
}
};
};
export const USER_logoUT = () => {};
请问有什么建议吗?
另外,我已经看到我没有包装它重定向的组件,但未经授权
谢谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)