在 Redux 容器中使用高阶组件
Using higher order components with Redux containers
首先,一些背景。
我正在使用 Redux 来管理我的应用程序的身份验证状态,并将 Auth
作为 Redux 容器(或智能组件)。
我创建了一个包装器(高阶组件),它采用 Auth
和 returns 它:
export default function AuthWrapper(WrappedComponent) {
class Auth extends Component {
... <Auth stuff here> ...
}
return connect(mapStateToProps, mapDispatchToProps)(Auth);
}
在我看来,为了使用包装器,我只需要使用我想要在我的身份验证背后的组件来调用它。例如,假设我正在使用包装器验证名为 UserPage
的组件,la:
const AuthenticatedUserPage = AuthWappper(UserPage)
但是,当我这样使用包装器时,React 对我不满意。我收到以下错误:
Warning: AuthenticatedApp(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
我最好的猜测是它不喜欢当我从 AuthWrapper
中 return 时 Redux 将创建的 connect
化组件...问题:
当那些组件创建 Redux 容器时,React 是否支持高阶组件?如果是这样,为什么 React 会抛出这个错误?
这是我的两分钱。我认为错误发生在其他地方。
根据 react-redux 中 connect
函数的简化版本,connect 函数只是 returning 另一个 React 组件。因此,在您的情况下,您正在 return 一个组件,包裹在另一个组件中 ,它仍然有效。 容器基本上就是一个组件。
阅读 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()
与错误状态一样,您可能只是 return在您的应用中的某处添加了无效组件。您的应用程序可能会抛出错误,因为您没有将 return 调用包装在您的渲染方法的括号中。
首先,一些背景。
我正在使用 Redux 来管理我的应用程序的身份验证状态,并将 Auth
作为 Redux 容器(或智能组件)。
我创建了一个包装器(高阶组件),它采用 Auth
和 returns 它:
export default function AuthWrapper(WrappedComponent) {
class Auth extends Component {
... <Auth stuff here> ...
}
return connect(mapStateToProps, mapDispatchToProps)(Auth);
}
在我看来,为了使用包装器,我只需要使用我想要在我的身份验证背后的组件来调用它。例如,假设我正在使用包装器验证名为 UserPage
的组件,la:
const AuthenticatedUserPage = AuthWappper(UserPage)
但是,当我这样使用包装器时,React 对我不满意。我收到以下错误:
Warning: AuthenticatedApp(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
我最好的猜测是它不喜欢当我从 AuthWrapper
中 return 时 Redux 将创建的 connect
化组件...问题:
当那些组件创建 Redux 容器时,React 是否支持高阶组件?如果是这样,为什么 React 会抛出这个错误?
这是我的两分钱。我认为错误发生在其他地方。
根据 react-redux 中 connect
函数的简化版本,connect 函数只是 returning 另一个 React 组件。因此,在您的情况下,您正在 return 一个组件,包裹在另一个组件中 ,它仍然有效。 容器基本上就是一个组件。
阅读 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()
与错误状态一样,您可能只是 return在您的应用中的某处添加了无效组件。您的应用程序可能会抛出错误,因为您没有将 return 调用包装在您的渲染方法的括号中。