【发布时间】:2020-12-31 12:22:36
【问题描述】:
我想从另一个函数中获取结果,因为我使用了异步等待,函数但它没有返回数据,这里我已经上传了代码,任何人都可以检查我的代码并帮助解决这个问题,我已调用此函数 data_json = await this.get_json_data(url_string); 但我没有从中获得任何返回数据
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoaded: false
};
}
async get_json_data(url_string) {
await fetch("https://cors-anywhere.herokuapp.com/" + url_string)
.then(res => res.text())
.then(
result => {
let final_data = JSON.parse(result);
return final_data;
},
error => {}
);
}
async componentDidMount() {
let data_json = "";
let url_string = location.search.split("url=")[1];
if (typeof url_string != "undefined" && url_string != undefined) {
data_json = await this.get_json_data(url_string);
//console.log("get result")
//console.log(data_json)
} else {
data_json = require("./data.json");
}
}
}
【问题讨论】:
-
你试过
res.json()而不是res.text()吗?有了这个,你不应该需要JSON.parse(result)。
标签: reactjs react-redux