我需要在React的render()函数中使用异步函数。我该怎么办?很明显,我现在得到的只是一个承诺。
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 />;
}
}
答案 0 :(得分:3)
您的异步函数返回的Promise无法与src一起使用。您可以在状态中存储该值并使用它。
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 />;
}
}
答案 1 :(得分:1)
您应该在componentDidMount生命周期方法中进行此类操作。
你可以试试这个吗?
import React, { Component } from "react";
export default class FlagImage extends Component {
state = {
url = ''
};
componentDidMount () {
let url = this.getSrc();
this.setState({
url
});
}
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.state.url} /> : <div />;
}
}
答案 2 :(得分:1)
在生命周期方法内调用该函数
componentDidMount(){
this.getSrc();
}