Разрушение с помощью unstated.js

У меня есть этот неустановленный контейнер:

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 });
  }
}

И эта функция, которая использует это:

static renderCurrencies() {
  return (
    <Subscribe to={[CurrenciesContainer]}>
      {(currencies) => {
        if (!currencies.state.currencies) {
          currencies.fetch();
        }
        return <small>Currencies: {currencies.state.currencies}</small>;
      }}
    </Subscribe>
  );
}

Я хотел попытаться разрушить параметры, поступающие в <Subscribe> вот так:

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

Ясно, что это не связывает должным образом, но я не уверен, почему деструктуризация функции изменила бы ее связывание. Кто-нибудь может предложить объяснение / способ сделать это так? Спасибо!

1 ответ

Решение

Замещать async fetch() {} с участием fetch = async () => {} добиться правильного связывания.

Попробуйте это в вашем Unstated контейнере:

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 });
 }
}
Другие вопросы по тегам