简体   繁体   中英

Destructuring with unstated.js

I have this Unstated container:

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

And this function that utilises it:

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

I wanted to try and destructure the params coming into the <Subscribe> like so:

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

But this breaks with Uncaught (in promise) TypeError: this.setState is not a function

Clearly it's not binding properly but I'm not sure why the destructuring of the function would change its binding. Anyone able to offer an explanation/way of doing it like this? Thanks!

Replace async fetch() {} with fetch = async () => {} to achieve the correct binding.

Try this in your Unstated container:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM