1

我有这个未说明的容器:

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

显然它没有正确绑定,但我不确定为什么函数的解构会改变它的绑定。任何人都能够提供这样的解释/方式吗?谢谢!

4

1 回答 1

2

替换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 });
 }
}
于 2019-08-29T10:39:04.480 回答