Создание множественного запроса от HOC в реагировать - PullRequest
0 голосов
/ 23 мая 2018

Я хотел создать несколько запросов из hoc, где я смог создать hoc для одного запроса (действие примитива, которое вызывает API), пожалуйста, проверьте код для одного запроса

Я создал hoc для уменьшения повторениякод в каждом компоненте, например, на componentdidmount вызов API, управление ошибкой, управление состоянием загрузки, но это только для одного запроса, как вы можете видеть в первоначальном объекте в данном случае, поэтому я хочу создать объект, который может выполняться для нескольких запросов(избыточное действие, вызывающее api), я не знаю, правильно ли реализовано это решение, работающее для одного запроса, или нет

Итак, пожалуйста, помогите мне создать hoc, который можно повторно запечатать для любого данного сценария

hoc

export const ComponentWithAPIRequest = ({ onMount = null, LoaderRequestID,onUnmount = null }) => (WrappedComponent) => {
return class ComponentWithAPIRequest extends Component {
    state = {
        stateLoader: true // intial Load
    };
    componentDidMount = () => {
        this.Request();
    };

    componentWillUnmount() {
        onUnmount !== null ? this.props[onUnmount]() : null;
    }

    Request = () => {
        onMount !== null ? this.props[onMount](LoaderRequestID) : null; // API request
        this.setState({ stateLoader: false });
    };

    render() {
        const { error, isLoading } = this.props; // pass it here somehow.
        const { stateLoader } = this.state;
        const isLoadingFromAPI = this.props.isLoadingRequestIds.indexOf(LoaderRequestID) !== -1 ? true : false;

        if (stateLoader) {
            return (
                <div className="text-center">
                    <CircularProgress />
                </div>
            );
        }
        if (isLoadingFromAPI) {
            return (
                <div className="text-center">
                    <CircularProgress />
                </div>
            );
        } else {
            return <WrappedComponent {...this.props} retry={this.Request} />;
        }
    }
};
};

компонент

export const isContainer = ({ intial, list }) => (WrappedComponent) => {
 const IsContainer = (props) => <WrappedComponent {...props} />;
 return compose(ComponentWithAPIRequest(intial), hasRequestError) 
 (IsContainer);
};



hasRequestError // is error hoc
ComponentWithAPIRequest // is above added hoc



@isContainer({
intial: {
    onMount: 'FirstRequest', // is a redux action which call api,here i want to have multiple request like ['FirstRequest','SecondRequest'] 
    LoaderRequestID: 'FirstRequestLoader', // is an unique id for loader,which then for multiple request be converted to respective request like ['FirstRequestLoader','SecondRequestLoader'] 
    onUnmount: 'ResetLeaderBoardAll' // is a redux action when component unmount
}
 })
class ComponentView extends Component {
render() {
    return (
            <SomeComponent {...this.props}/>
    );
 }
}

 const mapStateToProps = (state) => {

   return {
    somestate:state
   };
 };



export default connect(mapStateToProps, {
 FirstRequest,
 SecondRequest
})(ComponentView);

1 Ответ

0 голосов
/ 23 мая 2018

На вашем месте я бы обновил ваш hoc и передал бы несколько URL-адресов в качестве параметра для отправки нескольких запросов, таких как:

export default connect(mapStateToProps, mapDispatchToProps)(ComponentWithAPIRequest(ComponentView,
    [
       "url1", "url2" ... 
    ]));

И передал бы их обратно в ComponentView с помощью 'props' или 'props.requestResponses'(одиночный) объект.Тогда я бы использовал их как

const url1response = this.props.requestResponses["url1"];

В моем случае я бы сохранил их в состоянии ComponentWithAPIRequest, но вы можете использовать redux и получить их из mapStateToProps в ComponentView.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...