获取 React Native 意外令牌 [英] Fetch React Native unexpected token

查看:36
本文介绍了获取 React Native 意外令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的应用程序,该应用程序从 facebook 演示 api 中检索数据并使用 react native 显示它们.

I'm trying to create a simple app the retrieves data from a facebook demo api and displays them with react native.

这是我的代码(用于 index.android.js):

This is my code (for index.android.js) :

import React, { Component } from 'react';
import { AppRegistry, Text , View } from 'react-native';

class AwesomeProject extends Component{


  constructor(props){
    super(props);
    this.state = {
      movies: []
    }

  };

  componentWillMount(){
      this.getMoviesFromApi().then((res) => {
          movies: res.movies;
      });
  }



   async function getMoviesFromApi() {
    try {
      let response = await fetch('https://facebook.github.io/react-native/movies.json');
      let responseJson = await response.json();
      return responseJson.movies;
    } catch(error) {
      console.error(error);
    }
  }



  render() {

      return(
          <Text>
            {this.state.movies}
          </Text>
        );

  }

}
AppRegistry.registerComponent('AwesomeProject',() => AwesomeProject);

但它一直给我这个错误:

But it keeps giving me this error:

Unexcepted token, excpected ( (28:18) index.android.js:23:18

推荐答案

您的代码中存在一些错误.
1. 使用 setState 更新电影属性.

There are a few mistakes in your code.
1. Use setState to update movies property.

  this.getMoviesFromApi().then((res) => {
    this.setState({
      movies: res
    });
  });

2.async function getMoviesFromApi() 应该只是 async getMoviesFromApi()
3. 在render 函数中,将Text 包裹在View 中并循环遍历movies 数组.示例 -

2. async function getMoviesFromApi() should be just async getMoviesFromApi()
3. In render function, wrap Text inside View and loop through movies array. Example -

  return(
    <View>
      {this.state.movies.map(m => (
        <Text key={m.title}> {m.title} </Text>))}
    </View>
  );

这篇关于获取 React Native 意外令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆