首先,一些上下文。
我正在使用redux来管理应用程序的身份验证状态,并将Auth
作为redux容器(或智能组件)。
我已经创建了一个服用Auth
并返回的包装器(一个高阶组件):
export default function AuthWrapper(WrappedComponent) {
class Auth extends Component {
... <Auth stuff here> ...
}
return connect(mapStateToProps, mapDispatchToProps)(Auth);
}
在我看来,要使用包装纸,我只需要用我想在auth后面拥有的组件调用它。例如,假设我正在验证一个名为 UserPage
的组件,用包装器,àla:
const AuthenticatedUserPage = AuthWappper(UserPage)
但是,当我使用这样的包装器时,对我不满意。我收到以下错误:
Warning: AuthenticatedApp(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
我最好的猜测是,当我从AuthWrapper
返回时,Redux会创建的connect
配置组件...这使我遇到了我的问题:
当这些组件创建REDUX容器时,React会支持高阶组件吗?如果是这样,为什么要抛出此错误?
这是我的两美分。我认为错误是在其他地方发生的。
根据React-Redux中connect
函数的简化版本,连接函数只是返回另一个React组件。因此,在您的情况下,您要返回一个组件,包裹在另一个组件中,这仍然是有效的。容器基本上是组件。
阅读https://gist.github.com/gaearon/1D19088790E70AC32EA636C025BA424E,以更好地了解连接功能。
我还在自己的应用程序中尝试了以下内容,并且它起作用。
import Layout from '../components/Layout'
//Do some other imports and stuff
function wrapper(Layout) {
return connect(null, mapDispatchToProps)(Layout);
}
export default wrapper()
就像错误状态一样,您可能只是仅仅在应用程序中的某个地方返回一个无效的组件。您的应用程序可能会引发错误,因为您没有在渲染方法上用括号中包装返回调用。