如何处理 json 数据放入 numColumns={2} 的 FlatList?

How to deal with json data put it into FlatList with numColumns={2}?

我问过类似的问题,但我发现我真正的问题是如何处理我的 jsondata 和 return 它。

就我而言,我不知道如何映射数据并 return 只有一个 <View>。在我的函数 renderRow 中,它看起来像我 return 两个 <View> 因为我无法在 FlatList 中设置 numColumns={2}。它将显示错误 Element type is invalid

任何人都可以将我从世界上拯救出来。我卡在这里了。

这是我的 App.js 我获取一个 API 来获取 jsondata:

import React from 'react';
import { View, Image, FlatList } from 'react-native';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.renderRow = this.renderRow.bind(this);
    this.state = { movies: [] };
  }

  componentWillMount() {
    fetch('https://obscure-reaches-65656.herokuapp.com/api?city=ThisWeek')
      .then(response => response.json())
      .then(responseData => {
        console.log(responseData);
        this.setState({ movies: responseData });
      })
      .catch((error) => console.log(error));
  }

  renderRow(movies) {
    console.log('renderRow => ');
    console.log(movies)
    return movies.item.movie.map(movie => 
      <View>
        <Image source={{ uri: movie.photoHref}} style={{ height: 150, width: 150 }} />
      </View>
    );
  }

  render() {
    const movies = this.state.movies;
    console.log('render');
    console.log(movies);
    return (
      <View style={{ flex: 1 }}>
        <FlatList
          data={movies}
          renderItem={this.renderRow}
          horizontal={false}
          keyExtractor={(item, index) => index}
          numColumns={2}
        />
      </View>
    );
  }
}

这是我的调试控制台:

您需要正确使用您的响应数据,我做了一些更改并且每行能够看到 2 个图像,这里是更改

更改了将电影设置为状态的方式

this.setState({ movies: responseData[0].movie });

访问responseData[0]之前需要注意一下,我访问就是为了看结果

renderRow 更改如下

renderRow({item: movie}) {
    return (
       <View>
           <Image source={{ uri: movie.photoHref}} style={{ height: 150, width: 150 }} />
       </View>
    );
}

照样休息。

希望对您有所帮助!