我需要在 React 的 render() 函数中使用异步函数。我怎么能那样做?显然,我现在得到的只是一个 Promise。
import React, { Component } from "react";
export default class FlagImage extends Component {
getSrc = async name => {
const url = `https://restcountries.eu/rest/v2/alpha/${name}`;
const res = await fetch(url);
const json = res.json();
const flagURL = json.flag;
return flagURL;
};
render() {
const { name } = this.props;
return name ? <img alt={`Flag ${name}`} src={this.getSrc(name)} /> : <div />;
}
}
您的异步函数返回无法与 src 一起使用的承诺。您可以将该值存储在 state 中并使用它。
import React, { Component } from "react";
export default class FlagImage extends Component {
state = { imageSrc: "" }
getSrc = async name => {
const url = `https://restcountries.eu/rest/v2/alpha/${name}`;
const res = await fetch(url);
const json = res.json();
const flagURL = json.flag;
setState({imageSrc: flagURL})
};
componentDidMount() {
this.getSrc();
}
render() {
const { name } = this.props;
return name ? <img alt={`Flag ${name}`} src={this.state.imageSrc} /> : <div />;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句