Redux Connect w/ HOC - 类型错误:无法设置未定义的属性"props"



我正在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和connect,它看起来像这样,并且可以完美运行。

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);

这非常有效! 🙂

connect希望将 React 组件作为最后一个参数,但您正在发送 HOC 。您需要将connect和包装器放入函数compose。见下文

import React from 'react'
import {compose} from 'redux'
import {connect} from 'react-redux'
import {doSomething} from './actions'
const wrapComponent = Component => {
const WrappedComponent = props => {
return (
<Component {...props} />
)
}
return WrappedComponent
}
const mapStateToProps = state => {
return {
prop: state.prop,
}
}
export default compose(
connect(mapStateToProps, {doSomething}),
wrapComponent
)

和这样的使用。

import React from 'react'
import withWrapper from 'your/path'
const Component = props => 'Component'
export default withWrapper(Component)

相关内容

最新更新