简体   繁体   English

如何从功能组件中调用类组件

[英]How to call class component from the functional component

Here I want to show a modal window (which is class component) when a request fails in axios interceptor response. 在这里,我想显示一个请求窗口在axios拦截器响应中失败时的模式窗口(这是类组件)。 Can anyone help me how to call Modals class instead of alerts in the below code. 任何人都可以帮助我如何调用Modals类,而不是以下代码中的警报。

     //axios interceptor 
    import React, { Component}  from 'react';
    import axios from 'axios';
    import Modals  from '../components/modalAlerts/modalalerts';
    import ReactDOM from 'react-dom';
    import ShallowRenderer from 'react-test-renderer/shallow'
    import { Button, Card, CardBody, CardHeader, Col, Modal, ModalBody, ModalFooter, ModalHeader, Row } from 'reactstrap';
    const instance = axios.create({
        baseURL: '//some url here',
        timeout: 15000,
    });
    instance.defaults.headers.common['Authorization'] = //token;
    instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    instance.interceptors.request.use(function (config) {
        return config;
      }, function (error) {
        alert(error)
        console.log(error.response)
        return Promise.reject(error);
      });
    instance.interceptors.response.use(function (config) {
        return config;
      }, function (error) {
        console.log(error)
        if(error.response){
            if(error.response.status === 401||error.response.status === 403 ){
                console.log("401")
                localStorage.clear()
                window.location = '/#/login';
                alert(error.response.data.message)
            }else if(error.response.status === 404){
               alert(404);
            }else if(error.response.status === 400){
               alert(error.response.data.message)
            }else{
                alert("something went wrong. Please try after sometime..!")
            }
        }else{
            alert("server not found")
        }

        return Promise.reject(error);
      });
    export default instance;

here my model class component I want to call this modal from above axios interceptor instead of alerts. 这是我的模型类组件,我想从axios拦截器上方而不是警报中调用此模式。

     class Modals extends Component {
        constructor(props) {
            super(props);
            console.log(props)
            this.state = {
                modal: true,
            }    
            this.toggle = this.toggle.bind(this);
        }

        toggle() {
            this.setState({
                modal: !this.state.modal,
            });
        }
        render() {
            return (
                <div className="animated fadeIn">
                    <Row>
                        <Col>
                            <Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
                                <ModalHeader toggle={this.toggle}>{this.props.apistatus == 1? "Success" : "Error"}</ModalHeader>
                                <ModalBody>
                                    {this.props.apistatus == 1? "Form updated successfully" : this.props.errormsg}
                                </ModalBody>
                                <ModalFooter>
                                    <Button color="primary" onClick={this.toggle}>OK</Button>{' '}
                                    {/* <Button color="secondary" onClick={this.toggle}>Cancel</Button> */}
                                </ModalFooter>
                            </Modal>       
                        </Col>
                    </Row>
                </div>
            );
        }
    }
    export default Modals;

This problem is similar to this one . 这个问题与类似。 There is Axios instance that is unrelated to React application, so it cannot get modal instance to interact with it. 有一个与React应用程序无关的Axios实例,因此它无法获取模式实例与之交互。 Binding it to React component instances would be a mistake that may result in other problems, eg in tests. 将其绑定到React组件实例将是一个错误,可能会导致其他问题,例如在测试中。 A proper approach is to associate Axios instance with specific application instance and provide Axios instance for entire application. 正确的方法是将Axios实例与特定的应用程序实例相关联,并为整个应用程序提供Axios实例。

Common ways to do this are deeply passed props, context API and global state management (Redux, MobX). 常用的方法是深入传递道具,上下文API和全局状态管理(Redux,MobX)。

Eg Axios factory function receives modal component instance to refer it: 例如,Axios工厂功能接收模态组件实例来引用它:

function axiosFactory(modalRef) {
      const instance = ...;
      instance.interceptors.request.use(..., function (error) {
        const modalInstance = modalRef.current;
        modalInstance.toggle();
      });
      ...
    }

const AxiosContext = React.createContext();

class App extends Component {
  modalRef = React.createRef();

  render() {
    return <>
      <Modal ref={this.modalRef}/>
      <AxiosContext.Provider value={axiosFactory(this.modalRef)}>
        ...the rest of the app that depends on Axios...
      </AxiosContext.Provider>
    </>;
  }
}

Axios instance can be retrieved in child components: 可以在子组件中检索Axios实例:

 <AxiosContext.Consumer>{axios => (
   <ComponentThatNeedsToGetAxiosAsProp axios={axios} />
 )</AxiosContext.Consumer>

Reusability may be improved with idiomatic React recipes, eg withAxios higher-order component that makes use of <AxiosContext.Consumer> as shown above. 可重用性可以与惯用的配方来提高反应,例如withAxios高次成分,使得使用的<AxiosContext.Consumer>如上所示。

In case of Redux this may be even simpler because Axios instance can become available in Redux store and be decoupled from React component hierarchy. 在Redux的情况下,这可能甚至更简单,因为Axios实例可以在Redux存储中变得可用,并且可以与React组件层次结构分离。 It doesn't need to get modal component directly because it can interact with it via actions. 它不需要直接获取模态组件,因为它可以通过动作与其进行交互。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从父功能组件调用 class 子组件方法 - Call class child component method from parent functional component 如何使用 onClick 事件调用基于 class 的组件中的功能组件? - how to call functional component in class based component using onClick event? 如何从功能组件中调用调度程序? - How to call a dispatcher from a functional component? ReactJS class 组件和功能组件如何从普通 Javascript ZC1C425268E68385D1AB50741? - How do I call ReactJS class component and functional component from normal Javascript function? 如何从一个反应功能组件调用功能方法到另一个反应功能组件? - How to call a functional method from one react functional component to another react functional component? 如何将代码片段从类组件更改为功能组件 - How to change a snippets of code from Class Component to Functional Component 如何将值从子功能组件传递给父类组件? - How to pass value from a child functional component to parent class component? 如何从类组件(父)更改功能组件(子)中的 useState - How to change useState in functional component (child) from class component (parent) 如何从功能组件访问 class 组件中的数组? - How can access an array in the class component from functional component? 如何使用useContext从功能组件更新class组件的state - How to update state of class component from functional component using useContext
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM