首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用unstated.js解构

用unstated.js解构
EN

Stack Overflow用户
提问于 2019-08-29 10:27:26
回答 1查看 74关注 0票数 1

我有一个未声明的容器:

代码语言:javascript
复制
import { Container } from 'unstated';
import axios from 'axios';

export default class CurrenciesContainer extends Container {
  state = { currencies: null };
  async fetch() {
    const { data: currencies } = await axios.get('http://localhost:8080/get-currencies');
    this.setState({ currencies });
  }
}

利用它的这个功能:

代码语言:javascript
复制
static renderCurrencies() {
  return (
    <Subscribe to={[CurrenciesContainer]}>
      {(currencies) => {
        if (!currencies.state.currencies) {
          currencies.fetch();
        }
        return <small>Currencies: {currencies.state.currencies}</small>;
      }}
    </Subscribe>
  );
}

我想尝试对进入<Subscribe>的params进行如下的重构:

代码语言:javascript
复制
static renderCurrencies() {
  return (
    <Subscribe to={[CurrenciesContainer]}>
      {({ state, fetch }) => {
        if (!state.currencies) {
          fetch();
        }
        return <small>Currencies: {state.currencies}</small>;
      }}
    </Subscribe>
  );
}

但这与Uncaught (in promise) TypeError: this.setState is not a function不同

显然,它没有正确地绑定,但是我不知道为什么函数的破坏会改变它的绑定。有人能给出这样的解释/方法吗?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-29 10:39:04

async fetch() {}替换为fetch = async () => {},以实现正确的绑定。

在未声明的容器中尝试以下操作:

代码语言:javascript
复制
import { Container } from 'unstated';
import axios from 'axios';

export default class CurrenciesContainer extends Container {
  state = { currencies: null };
  fetch = async () => {
    const { data: currencies } = await axios.get('http://localhost:8080/get-currencies');
    this.setState({ currencies });
 }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57708177

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档