【发布时间】:2017-01-06 13:43:20
【问题描述】:
学习 JavaScript 和 React Native,我似乎不明白如何将 json 响应放入我可以访问的变量中。我查看了this、this、this 以及 Mozilla 文档以及 this 等等,但似乎仍然没有掌握这个概念或让它发挥作用。
export default class AwesomeApp extends Component {
constructor(props) {
super(props);
this.state = { questions: [] };
}
componentWillMount() {
this.getQuestionsFromAPI().then((res) => {
this.setState({
questions: res
});
});
let url = 'http://127.0.0.1:3000/trivia';
async function getQuestionsFromAPI() {
fetch(url).then(response => response.json())
.then(function(json) {
questions = json;
//console.log(questions[0]);
return questions;})
.catch(error => console.log(error));
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.question}>
{ this.props.questions[0] }
</Text>
<View style={{ flex: 1, padding: 20 }}>
<CheckBox
label={ this.props.questions }
checked={false}
onChange={(checked) => console.log('I am checked', checked)}
/>
</View>
AppRegistry.registerComponent('AwesomeApp', () => AwesomeApp);
我收到错误“未定义不是函数(评估 'this.getQuestionsFromAPI()')。在浏览器中查看它,设置: var quests = getQuestionsFromAPI() 返回一个承诺
Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: undefined}
同时
console.log(questions[0]);
返回一个我想要的对象。我不明白什么?
【问题讨论】:
-
您没有在 getQuestionsFromAPI 中返回承诺。尝试在第一行添加
return。您能否也重新缩进您的代码,目前尚不清楚这些函数属于哪个对象。 -
你的意思是函数调用后? [
return fetch(url)...],我在android模拟器中得到undefined is not a function(evaluating 'this.getQuestionsFromAPI()'),但在浏览器中它返回PromiseStatus: resolved和PromiseValue: Array[4]。我的挑战是把它变成一个变量来显示。