Javascript 从URL获取JSON数据-格式问题
我在一个问题中看到了有用的代码:Javascript 从URL获取JSON数据-格式问题,javascript,reactjs,react-native,jsonschema,Javascript,Reactjs,React Native,Jsonschema,我在一个问题中看到了有用的代码: getSchemaFromApiAsync() { return fetch('https://facebook.github.io/react-native/movies.json') .then(response => response.json()) .then(responseJson => { return responseJson; }) .catch(error =
getSchemaFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then(response => response.json())
.then(responseJson => {
return responseJson;
})
.catch(error => {
console.error(error);
});
}
我有一个问题:我想把我的responseJson作为一个js对象,或者把它转换成一个js对象。我尝试了JSON.stringify,但不起作用。有什么想法吗?您的返回值是promise函数
constructor(props) {
super(props);
this.state = {};
}
componentWillMount(){
this.getObject();
}
getObject(){
return fetch('https://facebook.github.io/react-native/movies.json')
.then(response => response.json())
.then(responseJson => {
this.setState({responseJson : responseJson});
return responseJson;
})
.catch(error => {
console.error(error);
});
}
现在您的状态已设置。您可以随时访问此状态变量(另一个组件)。使用ES6语法尝试此操作,希望您有最新的库支持此操作
let getSchemaFromApiAsync = () => {
return new Promise((resolve, reject) => {
fetch('https://facebook.github.io/react-native/movies.json')
.then(response => resolve(response.json()))
.catch(error => {
console.error(error);
reject(error);
});
})
}
let main = async () => {
let res = await getSchemaFromApiAsync();
console.log("res", res);
};
main();
尝试在相关的RESTAPI中更改它。在nodejs文件中使用json.stringyfy。
将您的json响应设置为作用域。您也可以粘贴您的响应吗?和console.log(responseJson)@oma Promise{}proto:Promise-catch:ƒcatch()构造函数:ƒPromise()最终:ƒfinally()然后:ƒthen()Symbol(Symbol.toStringTag):“Promise”proto:Object[[PromiseStatus]]:“已解析”[[PromiseValue]]: undefined@ZeroCho看看答案。承诺函数。如何实现?ur componentWillMount()再次返回一个值,例如,在console.log(rs)之后返回this.setState({rs});我刚刚编写了一个componentWillMount(),目的是为了理解,您可以使用任何您想要的(函数)。@ZeroCho它再次返回一个promise fun。如果你不确定,请不要回答。告诉我你是如何称呼你的方法的?不幸的是,它不支持这个库。同样,console.log(“res”,res);返回承诺func和console.log(main());返回未定义的。