我有一个未声明的容器:
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>的params进行如下的重构:
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不同
显然,它没有正确地绑定,但是我不知道为什么函数的破坏会改变它的绑定。有人能给出这样的解释/方法吗?谢谢!
发布于 2019-08-29 10:39:04
将async fetch() {}替换为fetch = async () => {},以实现正确的绑定。
在未声明的容器中尝试以下操作:
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 });
}
}https://stackoverflow.com/questions/57708177
复制相似问题