【问题标题】:Load fetch into a variable React Native将 fetch 加载到变量 React Native
【发布时间】:2017-01-06 13:43:20
【问题描述】:

学习 JavaScript 和 React Native,我似乎不明白如何将 json 响应放入我可以访问的变量中。我查看了thisthisthis 以及 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: resolvedPromiseValue: Array[4]。我的挑战是把它变成一个变量来显示。

标签: javascript react-native


【解决方案1】:

您在上面发送的代码示例中存在一些问题。

首先,如果您正确缩进代码,您会注意到函数getQuestionsFromAPI 是在componentWillMount 中声明的。这意味着当您使用 this 引用它时,找不到它。

其次,getQuestionsFromAPI 不返回承诺。你应该return fetch(...)

最后,您尝试使用this.props.questions 获取问题,但您正在分配状态中的问题,因此您应该使用this.state.questions

【讨论】:

  • 谢谢,我最终使用了 ES5 和 getInitialState,因为我发现它们更容易理解,但比较你的答案,它们似乎实现了相同的目标。
猜你喜欢
  • 1970-01-01
  • 2017-11-22
  • 2018-08-18
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多