【问题标题】:connect react redux HOC got error of `Cannot call a class as a function`连接反应 redux HOC 出现“无法将类作为函数调用”的错误
【发布时间】:2018-09-17 22:57:40
【问题描述】:

下面我的 HOC 有什么问题?出现无法将类调用为函数的错误?

https://i.imgur.com/SirwcGZ.png

我的 HOC

const CheckPermission = (Component) => { 
    return class App extends Component { 
        componentDidMount() {
            this.props.fetchUsers().then(resp => {
                this.setState({user: true, loading: false});
            })
        } 
        render() { 
           const { user, loading } = this.props

           loading && <div>Loading...</div>

           !user && <Redirect to="/dashboard" />

           return <Component {...this.props} />
        }
    } 
}


export default connect(state=>state.global, {fetchUsers})(CheckPermission)

这就是我导入和使用 CheckPermission 的方式:

&lt;Route exact path='/dashboard' component={CheckPermission(Dashboard)} /&gt;

【问题讨论】:

    标签: javascript reactjs ecmascript-6 redux


    【解决方案1】:

    你不能用connect 包裹checkPermissions,因为它也是一个HOC。 相反,您必须编写它们。

    import { compose } from 'redux';
    

    ...

    export default compose(
      connect(state=>state.global, {fetchUsers}),  
      CheckPermission
    );
    

    【讨论】:

    • 我仍然遇到同样的错误,这是我的完整文件pastebin.com/HRdthN80
    • 第 7 行为什么要在 Component 周围添加花括号
    • 我编辑了我的代码 sn-p 以重新排序传递给 compose 的参数
    • 我删除了花括号,现在它可以工作了,撰写参数的顺序是否重要?
    • 是的,因为compose 将第二个函数的结果传递给第一个函数,而在checkPermission 中你需要connect 传递的props。
    猜你喜欢
    • 1970-01-01
    • 2020-02-11
    • 2018-09-10
    • 2019-03-07
    • 2020-12-01
    • 1970-01-01
    • 2018-03-10
    • 2018-04-30
    • 1970-01-01
    相关资源
    最近更新 更多