用 unstated.js 解构

Destructuring with 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

显然它没有正确绑定,但我不确定为什么函数的解构会改变它的绑定。任何人都可以提供 explanation/way 这样的做法吗?谢谢!

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