【问题标题】:React Native with RxJS使用 RxJS 反应原生
【发布时间】:2015-12-11 05:51:19
【问题描述】:

我一直在使用 React Native 和 RxJS,直到现在,每当我订阅我一直在做的 observable 时:

observable.subscribe(() => {
     this.setState({ loading: true });
}.bind(this));

但是自从我升级到 React Native 0.16.0 后,无论我在哪里对使用 ES2015 箭头符号声明的内联函数执行 bind(this),React Native 都会将其视为错误。但是,当我将箭头符号改回 ES5 常规函数符号时,如下所示:

observable.subscribe(function() => {
    this.setState({ loading: true });
}.bind(this));

错误似乎消失了。

这是怎么回事?

【问题讨论】:

  • 你想绑定什么this?这似乎是您只有在使用箭头函数时才需要做的事情?
  • .. 我和@azium 一起变老了。如果您编写 ()=>{},则外部作用域的 this 已绑定在函数中。

标签: android ios react-native rxjs


【解决方案1】:

当您使用箭头函数时,您已经将 this 绑定到该特定函数。所以:

() => {} === function() {}.bind(this)

【讨论】:

  • () => { return this }() === function() { return this }.bind(this)()
  • 这应该是最好的答案@coldbuffet
【解决方案2】:

与您的问题有关,我建议您还检查一下 FrintJS,它也带有 React 和 React Native 集成:https://github.com/frintjs/frint-react-native

它附带了一个 observe 高阶组件,它允许您使用 RxJS 可观察对象将 props 流式传输到您的组件,因此您的基础组件始终编写为无状态函数。

例子:

import React from 'react';
import { Observable } from 'rxjs';
import { observe } from 'frint-react';

function MyComponent(props) {
  return <p>Interval: {props.interval}</p>;
}

export default observe(function () {
  // return an Observable emitting a props-compatible object here
  return Observable.interval(1000)
    .map(x => ({ interval: x }));
})(MyComponent);

关于这个主题的更多信息:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多