获取JSON并在react-native中遍历值

15 浏览
0 Comments

获取JSON并在react-native中遍历值

我是React Native的新手,我试图简单地遍历一个示例的JSON文件,但是我收到了错误undefined is not a function (evaluating 'this.state.results.map')。我已经将初始状态设置为对象,所以不确定为什么会收到这个错误。

下面是JS代码:

import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View, StyleSheet, TouchableHighlight } from 'react-native';
var REQUEST_URL = 'https://facebook.github.io/react-native/movies.json';
class WPReact extends Component {
  constructor(props) {
    super(props);
    this.state = {results: []};
  }
  componentDidMount() {
    this.fetchData();
  }
  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          results : { responseData }
        });
      })
      .done();
  }
  render() {
    return this.renderJSON();
  }
  renderJSON() {
    contents = this.state.results.map((item) => {
      
        
          {item.movies.title}
        
      
     });
    return (
      
        {contents}
      
    );
  }
}
var Dimensions = require('Dimensions');
var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  textContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
  },
  text: {
    fontSize: 18,
    paddingLeft: 20,
    paddingRight: 20,
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
// App registration and rendering
AppRegistry.registerComponent('AwesomeProject', () => WPReact);


编辑

所以我已经编辑了`renderJSON()`方法,并且按照您的建议,已经删除了`responseData`周围的大括号,因为它已经是一个对象:

renderJSON() {
    console.log(this.state.results.description);
    contents = this.state.results.movies.map((item) => {
      
        
          {item.title}
        
      
     });
    return (
      
        {contents}
      
    );
  }

我添加了一个控制台日志来查看是否能够输出一些数据,我可以看到描述。我使用的示例JSON是(来自React的演示):

{

"title": "The Basics - Networking",

"description": "Your app fetched this from a remote endpoint!",

"movies": [

{ "title": "Star Wars", "releaseYear": "1977"},

{ "title": "Back to the Future", "releaseYear": "1985"},

{ "title": "The Matrix", "releaseYear": "1999"},

{ "title": "Inception", "releaseYear": "2010"},

{ "title": "Interstellar", "releaseYear": "2014"}

]

}

我可以打印出描述和标题。但是我仍然收到以下错误:ReactNativeJS: undefined is not an object (evaluating 'this.state.results.movies.map')。 如果我尝试打印console.log(this.state.results.movies[0].title),我收到undefined is not an object (evaluating 'this.state.results.movies[0]')的错误。

fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        console.log(responseData);
        this.setState({
          results : responseData
        });
      })
      .done();
  }

`console.log(responseData)`显示:

03-29 13:49:53.028  3062  4143 I ReactNativeJS: { title: 'The Basics - Networking',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   description: 'Your app fetched this from a remote endpoint!',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   movies: 
03-29 13:49:53.028  3062  4143 I ReactNativeJS:    [ { title: 'Star Wars', releaseYear: '1977' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Back to the Future', releaseYear: '1985' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'The Matrix', releaseYear: '1999' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Inception', releaseYear: '2010' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Interstellar', releaseYear: '2014' } ] }

`console.log(this.state.results.movies)`显示:

03-29 14:18:05.483  3062  4726 I ReactNativeJS: undefined
03-29 14:18:05.510  3062  4726 I ReactNativeJS: [ { title: 'Star Wars', releaseYear: '1977' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Back to the Future', releaseYear: '1985' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'The Matrix', releaseYear: '1999' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Inception', releaseYear: '2010' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Interstellar', releaseYear: '2014' } ]

0
0 Comments

问题的出现原因是responseData必须是一个数组才能在其上调用Array#map()方法。

解决方法是移除results周围的大括号,如果确保responseData是一个数组。然后在设置results属性时解析JSON数据。如果解析成功,可以调用map方法。

具体代码如下:

this.setState({ 
  results :  JSON.parse(responseData)
});

但是,如果解析responseData时出现JSON Parse error: Unexpected identifier "object"的错误,那么可能不需要解析代码。同时,需要检查在哪里调用了console.log(this.state.results.movies)来打印结果。

文章内容到此结束。

0
0 Comments

是的,this.fetch 也会失败。这是因为在 ES6 类中,this 不会自动绑定到非 React 方法。为了解决这个问题,可以在构造函数中添加以下代码:

this.fetch = this.fetch.bind(this)

0
0 Comments

在这段代码中,问题的出现原因是:

1. fetchData方法没有绑定,需要在构造函数中使用this.fetchData = this.fetchData.bind(this);进行绑定。

2. map方法应该应用于this.state.results.movies,因为它是一个数组。而this.state.results是一个包含数组的对象。

解决方法如下:

1. 在构造函数中使用this.fetchData = this.fetchData.bind(this);进行绑定。

2. 在render方法中使用this.state.results.movies.map()遍历数组。

以下是整理后的代码:

import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View, StyleSheet, TouchableHighlight } from 'react-native';
var REQUEST_URL = 'https://facebook.github.io/react-native/movies.json';
class WPReact extends Component {
  constructor(props) {
    super(props);
    this.state = {
      results: {
        title: '',
        description: '',
        movies: []
      }
    };
    this.fetchData = this.fetchData.bind(this);
  }
  componentDidMount() {
    this.fetchData();
  }
  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          results: responseData
        });
      })
      .done();
  }
  render() {
    contents = this.state.results.movies.map((item) => {
      return (
          
            
              {item.title}
            
          
        );
     });
    return (
      
        {contents}
      
    );
  }
}
var Dimensions = require('Dimensions');
var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  textContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
  },
  text: {
    fontSize: 18,
    paddingLeft: 20,
    paddingRight: 20,
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
AppRegistry.registerComponent('AwesomeProject', () => WPReact);

希望以上解决方法能帮助到你。

0