首页 > 解决方案 > 从 api restful 填充 flatlist

问题描述

我正在尝试从我的 api restful 中获取值并加载到我的平面列表中。但它不起作用。

import React from 'react';
import {
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  View,
  FlatList,
  Row
} from 'react-native';

export default function HomeScreen() {

  const highScores = fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
      console.log(responseJson.movies);
      return responseJson.movies;

    })
    .catch((error) => {
      console.error(error);
      alert(error);
    });

  return (
    <View style={styles.container}>

      <ScrollView
        style={styles.container}
        contentContainerStyle={styles.contentContainer}>

        <View>
          <FlatList
            data={highScores}
            renderItem={
              ({ item, index }) =>
                <Row highScore={item} index={index} key={index} />
            }
          />
        </View>

        );
    }

看一下,在我将加载到 highScores 并最终填充我的 FlatList 之后,我正在访问https://facebook.github.io/react-native/movies.json以获取他的数据。但它不起作用......有人可以帮我修复它吗?

标签: react-nativeexpo

解决方案


实际上,在渲染之后,您保存高分为时已晚。尝试使用状态和效果挂钩来保存高分并触发重新渲染。

function App() {
  const [highScores, setHighScores] = useState([]);

  useEffect(() => {
    fetch("https://facebook.github.io/react-native/movies.json")
      .then(response => response.json())
      .then(responseJson => {
        console.log(responseJson.movies);
        // return responseJson.movies;
        setHighScores(responseJson.movies);
      })
      .catch(error => {
        console.error(error);
        alert(error);
      });
  }, []);

  return (
    <div className="App">
      {highScores.map(({ title, releaseYear }, index) => (
        <div index={index} key={index}>
          {title}: {releaseYear}
        </div>
      ))}
    </div>
  );
}

编辑确定的diffie-1s2z0


推荐阅读