javascript - 如何从无渲染类 React-Native 调用函数

标签 javascript reactjs react-native redux

假设我有 A 类和 B 类

class A extends Component{
    render() {
        return null;
    }

    foo = (a) => {
        return a;
    }
}

...


export default connect(mapStateToProps, mapDispatchToProps)(A);

然后在B类中调用foo()

import A from 'path/to/A';

class B extends Component{
    let a;

    hey() {
        A.foo(a);
    }
}

它给了我

类型错误:_A.default 不是构造函数

我几乎尝试了一切。

  1. 尝试调用 new A().foo(a); 但没有成功。
  2. 尝试将 static 赋予 A 中的 funtion,例如 static foo = () => ... 但在这种情况下 它看不到 A 类的 props。(A 类 props 变为未定义)。
  3. 尝试导出类本身并单独导出 connect() 上的默认值等。

我的问题是,如何在 B 类上使用 A 类的函数。考虑到我在这两个类上都有 redux。 A 类是业务逻辑所在的位置,B 类处理 UI。

请不要关闭问题,因为 Stackoverflow 问题都没有解决我的问题。 提前致谢

<小时/>

编辑

假设我的 foo() 函数与全局状态和调度类似。

foo = () => {
    let length = this.props.prod.length;
    let id = this.props.prod[length-1].id + 1;

    this.props.addProd({name: 'LOADING', id: id});
}

this.props.prod 来自全局状态。 this.props.addProd() 是操作创建者,用于将 prod 推送到全局状态。

如果我不使用类来定义这个函数。如何在此函数中调用 actionCreator 或获取全局状态?

最佳答案

首先,你不需要把A做成一个组件,你可以像函数一样简单地导出然后在B中调用它:

export function foo(a) {
   return a;
}

然后在 B 中调用该函数

import { foo } from 'path/to/A';

class B extends Component{
    let a;

    hey() {
        foo(a);
    }
}

如果你需要在 foo 函数中使用 redux 状态,你可以将其作为参数传递,或者我建议使用 redux-sagas 。

关于javascript - 如何从无渲染类 React-Native 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60090132/

相关文章:

javascript - 跨源问题 AngularJS 在 Eclipse 中的指令

javascript - 为什么那个声音在手机上不起作用?

javascript - 为什么 eval() 代码中的语法错误被忽略?

javascript - 使用 npm 包导出我自己的流类型?

javascript - 获取错误 :unable to execute js call:_fbBatchedBridge is undefined while executing in simulator

reactjs - img 未显示在 reactstrap 轮播中

reactjs - 在 React js 中对 .map 数据进行排序(在顶部显示最新日期)

react-native - react native 错误 : Raw "" must be wrapped in an explicit <Text> Component

node.js - 如何使用状态在后端发出 POST 获取请求

javascript - 未捕获的类型错误 : Illegal constructor when using HTMDivElement class in JS