首页 > 解决方案 > 如何在 const export “function” 周围包装 HOC

问题描述

我有一个调用的 HOC withErrorHandler,它接受一个组件,axios它使用它并向它添加错误处理程序,这对于普通组件很容易

export default withErrorHandler(myComponent, axios); 

但是当导出语法和函数是这样的时候,我不知道如何做同样的事情:

//how can i wrap an hoc around this?
export const authenticationService = {
  login,
  logout,
  currentUser: currentUserSubject.asObservable(),
  get currentUserValue() { return currentUserSubject.value }
};

function login(username, password) {}

function logout() {}

更新 01:
我的 HOC 组件:

import React, { Component } from 'react';

import Dialog from '@material-ui/core/Dialog';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import Paper from '@material-ui/core/Paper';
// import Draggable from 'react-draggable';

// function PaperComponent(props) {
//     return (
//         <Draggable cancel={'[class*="MuiDialogContent-root"]'}>
//             <Paper {...props} />
//         </Draggable>
//     );
// }

const withErrorHandler = (WrappedComponent, axios) => {
    return class extends Component {
        state = {
            error: null
        }

        componentWillMount() {
            axios.interceptors.request.use(req => {
                this.setState({ error: null });
                return req;
            });

            axios.interceptors.response.use(res => res, error => {
                this.setState({ error: error });
            });
        }

        errorConfirmedHandler = (event) => {
            this.setState({ error: null });
        }

        render() {
            console.log('inside with error handler')
            return (
                <React.Fragment>

                    <Dialog
                        open={this.state.error}
                        onClose={this.errorConfirmedHandler}
                        //PaperComponent={PaperComponent}
                        aria-labelledby="draggable-dialog-title"
                    >
                    <DialogTitle style={{ cursor: 'move' }} id="draggable-dialog-title">
                            خطا
                    </DialogTitle>
                        <DialogContent>
                            <DialogContentText>
                                {this.state.error ? this.state.error.message : null}
                            </DialogContentText>
                        </DialogContent>
                    </Dialog>

                    <WrappedComponent {...this.props} />
                </React.Fragment>
            );
        }
    }
}

export default withErrorHandler;

标签: reactjsdesign-patterns

解决方案


推荐阅读