gpt4 book ai didi

javascript - 使用 unstated.js 进行解构

转载 作者:行者123 更新时间:2023-11-30 13:53:41 32 4
gpt4 key购买 nike

我有这个 Unstated 容器:

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

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

最佳答案

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

在你的 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 });
}
}

关于javascript - 使用 unstated.js 进行解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57708177/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com