2

Идет вечная загрузка и не отображается контент.

Ошибка в консоли хром введите сюда описание изображения

App.js

import React, { Component } from 'react';
import { ActivityIndicator, FlatList, Text, View, StyleSheet } from 'react-native';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true
    }
  }

  componentDidMount() {
    return fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
       // let ds = new FlatList.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.setState({
          isLoading: false,
          dataSource: ds.cloneWithRows(responseJson.movies),
        }, function() {
          // do something with new state
        });
      })
      .catch((error) => {
        console.error(error);
      });
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }

    return (
      <View style={{flex:1,justifyContent:'center'}}>
      <FlatList
      data={this.state.data}
      keyExtractor={this._keyExtractor}
      renderItem={({item}) => <Text> {item.Begin} </Text> }
      />
      </View>
    );
  }
}

1 ответ 1

1
+50

Какова цель использования DataSource и cloneWithRows? Правильно ли я понимаю - Вам нужно получить объект и вывести массив movies? Вы можете передать массив непосредственно в компонент:

Snack

import React, { memo, useState, useEffect } from 'react';
import { Text, View, FlatList, ActivityIndicator, StyleSheet } from 'react-native';
import Constants from 'expo-constants';


export default function App() {
  const [isLoading, setIsLoading] = useState(true);
  const [data, setData] = useState(null);

useEffect(() => {
    fetch('https://facebook.github.io/react-native/movies.json')
      .then(response => response.json())
      .then((responseJson) => {
        // const ds = new FlatList.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
        setIsLoading(false);
        setData(responseJson);
      }, () => {
        // do something with new state
      })
      .catch((error) => {
        console.error(error);
      });
  }, []);

  return (
    <View style={styles.container}>
     { 
       isLoading &&   
       <View style={{ flex: 1, paddingTop: 20 }}>
          <ActivityIndicator />
        </View>
      }
       { 
        !isLoading && 
          <View style={{ justifyContent: 'center', flex: 1 }}>
            <FlatList
              data={data?.movies}
              keyExtractor={item => item.id}
              ListHeaderComponent={() => (
                <View>
                  <Text style={{ color: 'blue', fontSize: 28, }}>{data?.title}</Text>
                  <Text style={{ color: 'brown', fontSize: 18, }}>{data?.description}</Text>
                </View>
              )}
              renderItem={({ item }) => (
                <Text style={styles.paragraph}>
                  {` - ${item?.title}: ${item?.releaseYear}`}
                </Text>
              )}
            />
          </View>
       }
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 14,
    fontSize: 18,
    fontWeight: 'bold',
  },
});

9
  • В json сейчас только один массив, а их будет много в этом файле. Вывести нужно по отдельности эти массивы.
    – steep
    5 мар 2021 в 3:56
  • А если json будет такого вида? Как настроить? { "title": "Kotori", "link": "charge.html", "category": "Dubstep", "image": "charge.jpg", } { "title": "Tisoki", "link": "royce.html", "category": "Trap", "image": "royce.jpg", }
    – steep
    7 мар 2021 в 7:31
  • И почему маленький массив выводит, а большой нет. 4 строки нормально, а уже 5 не выводит?
    – steep
    7 мар 2021 в 10:20
  • по п.1 - нужен пример json'a. Если это будет массив массивов, то тоже не вижу проблем с передачей во FlatList.
    – oknelvapi
    8 мар 2021 в 18:38
  • 1
    У вас не валидный json, поэтому он и не парсится - лишняя запятая после последнего элемента в массиве. Воспользуйтесь сервисом json.parser.online.fr и проверьте там ваш json.
    – oknelvapi
    9 мар 2021 в 8:31

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.