【发布时间】:2026-01-27 00:15:02
【问题描述】:
我正在 Next.js 中构建一个快速身份验证高阶组件,但遇到以下代码的一些问题:
import SignIn from "../components/sign-in";
import { connect } from "react-redux";
import { useRouter } from "next/router";
const AuthenticationCheck = WrappedComponent => {
const { isAuthenticated, ...rest } = props;
const router = useRouter();
const protectedPages = ["/colours", "/components"];
const pageProtected = protectedPages.includes(router.pathname);
return !isAuthenticated && pageProtected ? (
<SignIn />
) : (
<WrappedComponent {...rest} />
);
};
function mapStateToProps(state) {
return {
isAuthenticated: state.auth.isAuthenticated
};
}
export default connect(mapStateToProps)(AuthenticationCheck);
如果我更改代码以删除 redux 和连接,它看起来像这样,并且可以完美运行。
const AuthenticationCheck = WrappedComponent => {
const { ...rest } = props;
const router = useRouter();
const protectedPages = ["/colours", "/components"];
const pageProtected = protectedPages.includes(router.pathname);
return pageProtected ? <SignIn /> : <WrappedComponent {...rest} />;
};
export default AuthenticationCheck;
在过去的几个小时里,我一直在阅读所有 SO、redux 文档等,但我真的找不到任何与我正在做的事情相匹配的东西,尽管我不敢相信这是一个不常见的用例。
我是否遗漏了一些明显的东西?
解决方案:(感谢迪玛的帮助!)
所以最终运行的代码是:
import SignIn from "../components/sign-in";
import { connect } from "react-redux";
import { useRouter } from "next/router";
import { compose } from "redux";
const AuthenticationCheck = WrappedComponent => {
const authenticationCheck = props => {
const { isAuthenticated, ...rest } = props;
const router = useRouter();
const protectedPages = ["/colours", "/components"];
const pageProtected = protectedPages.includes(router.pathname);
return !isAuthenticated && pageProtected ? (
<SignIn />
) : (
<WrappedComponent {...rest} />
);
};
return authenticationCheck;
};
function mapStateToProps(state) {
return {
isAuthenticated: state.auth.isAuthenticated
};
}
export default compose(connect(mapStateToProps), AuthenticationCheck);
这很完美! ????
【问题讨论】:
-
您在哪一行得到错误?
-
如果有帮助,请随时接受答案。谢谢。
-
队友,你是冠军......我尝试了一个非常接近你答案的版本,但错过了最后一个逗号:“export default compose(connect(mapStateToProps, {doSomething) }), wrapComponent )" 现在我可以不用考虑这个就上床睡觉了……谢谢! ??????
-
谢谢。试试 eslint,它可以防止这种错误。
标签: javascript reactjs redux react-redux higher-order-components