我可能遗漏了一些东西,但我找不到任何示例如何将数据从HOC组件传递到另一个组件。 这是我的代码
import React from 'react'
import NoAccessPage from '../../pages/Admin/NoAccess';
import { menuItems } from '../../config/menu';
import {connect} from 'react-redux'
const AuthorizationHOC = (access) =>{
(WrappedComponent) =>
class WithAuthorization extends React.Component {
constructor(props) {
super(props)
this.state = {
user: {
accessItems: [
'reseptionPointsAccess',
'servicesAccess'
]
}
}
}
render() {
const { accessItems } = this.state.user;
let menuAccess = [];
menuItems.forEach(item => {
if (accessItems.includes(item.access)) {
menuAccess.push(item)
}
})
return (
<div>
{accessItems.includes(access) ? <WrappedComponent {...this.props} /> : <NoAccessPage/> }
</div>
)
}
}
}
const mapStateToProps = state => {
return {
menuArray: state
}
}
export default connect(mapStateToProps)(AuthorizationHOC)
&#13;
我想将数组menuAccess
传递给另一个组件,但我无法通过连接包裹AuthorizationHOC
。
我收到的控制台
Cannot call a class as a function
答案 0 :(得分:0)
您不需要使用connect包装HOC,您需要的是使用connect包装返回的组件
import React from 'react'
import NoAccessPage from '../../pages/Admin/NoAccess';
import { menuItems } from '../../config/menu';
import {connect} from 'react-redux'
const AuthorizationHOC = (access) =>{
(WrappedComponent) => {
class WithAuthorization extends React.Component {
constructor(props) {
super(props)
this.state = {
user: {
accessItems: [
'reseptionPointsAccess',
'servicesAccess'
]
}
}
}
render() {
const { accessItems } = this.state.user;
let menuAccess = [];
menuItems.forEach(item => {
if (accessItems.includes(item.access)) {
menuAccess.push(item)
}
})
return (
<div>
{accessItems.includes(access) ? <WrappedComponent {...this.props} /> : <NoAccessPage/> }
</div>
)
}
}
return connect(mapStateToProps)(WithAuthorization);
}
}
const mapStateToProps = state => {
return {
menuArray: state
}
}
export default AuthorizationHOC;
答案 1 :(得分:0)
Okey,我试过使用这段代码,现在我在控制台中遇到了这个错误:
(0 , _AuthorizationHOC2.default)(...) is not a function
在渲染我的HOC期间出现此错误
<Route path="/link" exact component={AuthorizationHOC('listOfOrdersAccess')(ListOfOrders)} />