我需要在 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 一起使用的 promise 。您可以将该值存储在状态中并使用它。
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 />;
}
}
关于javascript - 如何在React渲染中使用异步JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59456405/