在我的componentDidMount中,我调用随机引号api,它正确显示到控制台。然后我调用set state,但在unirest调用api之前调用set state。我怎么能等到api调用完成才能调用setState?
my_2d_array = []
my_2d_array.insert(0, Ne_initial)
my_2d_array.append(Ne_final)
答案 0 :(得分:1)
您可以在从API获取结果后调用setState,请查看以下代码:
componentDidMount() {
let data = [];
unirest.get("https://andruxnet-random-famous-quotes.p.mashape.com/?cat=famous&count=2")
.header("X-Mashape-Key", Mashable_Key)
.header("X-Mashape-Host", "andruxnet-random-famous-quotes.p.mashape.com")
.end(function (result) {
data = result.body[0];
console.log(data)
this.setState({
quote: data.quote,
author: data.author,
category: data.category
})
})
}