【问题标题】:Export function to another class with default export使用默认导出将函数导出到另一个类
【发布时间】:2020-09-10 07:31:11
【问题描述】:

我有两个班级Orders.jsapi.js。我需要在api.js 中调用ShowAlertWithDelay 但由于我已经有一个默认导出mapStateToProps 我无法使用另一个导出。下面是代码

Orders.js

class Order extends Component {

constructor(props) {
    super(props);
    getOrders: []
      }


ShowAlertWithDelay = () => {
ShowToast("location",3,5000);
  };

const mapStateToProps = (state) => ({
getOrders: state.User.getOrders ? state.User.getOrders : [],
deliveredorder: state.User.deliveredorder ? state.User.deliveredorder : [],
userData: state.User.userData ? state.User.userData : false,
selectedTabdeliverOrder: state.User.selectedTabdeliverOrder ? state.User.selectedTabdeliverOrder : false
});
export default connect(mapStateToProps)(Order);


api.js

class Api {
if(resp.data.RouteCompleted == 206){

//Need to call ShowAlertWithDelay(); here

}
}
export default Api;

【问题讨论】:

  • 请改进您的代码
  • 我是新来的原生反应。请为此提供帮助

标签: javascript reactjs react-native react-redux


【解决方案1】:

一个简单的方法是创建一个新文件来导出 ShowAlertWithDelay ShowAlertWithDelay.js

export const ShowAlertWithDelay = () => {
ShowToast("location",3,5000);
  };

在 Orders.js 和 api.js 中

import {ShowAlertWithDelay}  from './ShowAlertWithDelay.js'

当您使用“导出默认值”时,然后像这样导入

import ShowAlertWithDelay  from './ShowAlertWithDelay.js'

【讨论】:

  • 没有办法调用 Orders.js 本身吗?
【解决方案2】:

您可以通过在同一目录中创建 index.js 来索引您的 Orders.js,但您拥有独立于 Orders 类的“ShowAlertWithDelay”

Orders.js

export const ShowAlertWithDelay =() =>{
  ShowToast("location",3,5000)
}
export class Order extends Component {
  //
}

index.js

export default { Orders } from './Orders.js'
export { ShowAlertWithDelay as Something } from './Orders.js'

【讨论】:

    猜你喜欢
    • 2020-05-22
    • 2016-06-03
    • 2016-07-24
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多