FlatList未显示导致React native

a5g8bdjr  于 2023-05-29  发布在  React
关注(0)|答案(2)|浏览(123)

我是React native的新手,我试图创建一个简单的flatlist并从API https://dummyjson.com/products填充它,但它从来没有显示结果。这是我App.tsx代码

import React from 'react';
import type {PropsWithChildren} from 'react';
import {
  FlatList,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
} from 'react-native';
import ShopList from './ReusableComponents/ShopList';
import axios from 'axios';
import {
  Colors,
  DebugInstructions,
  Header,
  LearnMoreLinks,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';

type SectionProps = PropsWithChildren<{
  title: string;
}>;

function App(): JSX.Element {
  const isDarkMode = useColorScheme() === 'dark';

  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };

  const shops: ArrayLike<any> | null | undefined = []



    fetch('https://dummyjson.com/products')
    .then(response => response.json())//hat el jsonresponse law rege3
    .then(result => { shops })

    console.log({shops})

  
  return (
    
    <SafeAreaView style={backgroundStyle}>
      <StatusBar
        barStyle={isDarkMode ? 'light-content' : 'dark-content'}
        backgroundColor={backgroundStyle.backgroundColor}
      />
     
     <ShopList />
      
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
  },
  highlight: {
    fontWeight: '700',
  },
  edges: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    padding: 5,
    minWidth: 50
  }
});

export default App;

这里是商店列表代码

import React, {Component} from 'react';

import {
  View,
  FlatList,
  Image
} from 'react-native'
import ShopListRow from '/Users/nb29042/Desktop/React/DemoShop/ReusableComponents/ShopListRow';
import { ListItem, Avatar } from 'react-native-elements';

export default class ShopList extends Component {
  constructor(props){
    super(props);
    this.state = {
      shops: []
    }
  }

      fetchItem() {
        requestAnimationFrame(() =>
          fetch(`https://dummyjson.com/products`, {
            method: 'GET',
          })
            .then(response => response.json())
            .then(responseJson => {
              this.setState({shops: responseJson})
              // console.warn(this.state.shops);
            })
            .catch(error => {
              {
                alert(error)
              }
            }),
        );
    }
  
    componentDidMount(){
      this.fetchItem()
    }

    
      render() {
        return (

          <View style={{
            flex: 1,
            backgroundColor: '#FFFFFF'
          }}>
    
            
    
            <FlatList
              data = {
                this.state.shops
              }
              renderItem={({ item, index }) => 
                {
                  return <ShopListRow 
                  shop={item} 
                  index={index} 
              
                />}
                
    
              }
              keyExtractor={item => item.id}
              initialNumToRender={16}
              extraData={this.state}
            />

    
          </View>
        );
      }
}

ShopListRow代码为:

import React, {Component} from 'react';

import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableHighlight,
  FlatList,
  Image
} from 'react-native'
//import Stars from './Stars';
export default class ShopListRow extends Component {
    render() {

        const {
          shop,
          index
        } = this.props
        
        return (
          <View key={shop.id} style={{ backgroundColor: index % 2 === 0 ? 'white' : '#F3F3F7' }}>
    
            <View style={styles.row}>
              
    
              <View >
                <Text>{shop.title}</Text>
                <Text >{shop.description}</Text>
              </View>
    
              <View style={styles.edges}>
                
                <TouchableHighlight 
                  //onPress={this.infoPressed}
                  style={styles.button}
                  underlayColor='#5398DC'
                >
                  <Text style={styles.buttonText}>Info</Text>
                </TouchableHighlight>
    
    
              </View>
            </View>
    
          </View>
        )
      }
}

const styles = StyleSheet.create({
    row: {
      flexDirection: 'row'
    },
    edges: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      padding: 5,
      minWidth: 50
    },
    stars: {
      flex: 1,
      alignItems: 'center',
      flexDirection: 'row',
      justifyContent: 'flex-start',
      padding: 5,
      minWidth: 50
    },
    nameAddress: {
      flexDirection: 'column',
      flex: 8,
      padding: 5
    },
    addressText: {
      color: 'grey'
    },
    button: {
      borderWidth: 1,
      borderColor: '#0066CC',
      borderRadius: 14,
      paddingHorizontal: 10,
      paddingVertical: 3,
      backgroundColor: '#fff',
    },
    buttonText: {
      color: '#0066CC',
      fontSize: 12
    },
    info: {
      marginHorizontal: 40,
      marginVertical: 10,
      padding: 10,
      backgroundColor: '#fff',
      borderWidth: 1,
      borderColor: '#ddd',
      borderRadius: 4
    }
  })

如果有人能帮助我为什么flatlist结果没有显示任何结果,我将不胜感激...最好的问候

ajsxfq5m

ajsxfq5m1#

App.tsx中,您需要:从函数组件的顶层移除shops数组声明和fetch调用;在useEffect钩子中移动fetch调用,以便在组件挂载时获取数据。
ShopList.tsx中:
1.删除fetchItem()函数。
1.使用useState钩子将构造函数替换为初始状态声明。
1.将API调用移动到useEffect钩子,以便在组件挂载时获取数据。
若要解决此问题,您可以按如下方式更新代码:
App.tsx中:

import React, { useState, useEffect } from 'react';
import type { PropsWithChildren } from 'react';
import {
  FlatList,
  SafeAreaView,
  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
} from 'react-native';
import ShopList from './ReusableComponents/ShopList';

type SectionProps = PropsWithChildren<{
  title: string;
}>;

function App(): JSX.Element {
  const isDarkMode = useColorScheme() === 'dark';
  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };

  const [shops, setShops] = useState<any[]>([]);

  useEffect(() => {
    fetch('https://dummyjson.com/products')
      .then((response) => response.json())
      .then((result) => {
        setShops(result);
      })
      .catch((error) => {
        console.error(error);
      });
  }, []);

  return (
    <SafeAreaView style={backgroundStyle}>
      <StatusBar
        barStyle={isDarkMode ? 'light-content' : 'dark-content'}
        backgroundColor={backgroundStyle.backgroundColor}
      />
      <ShopList shops={shops} />
    </SafeAreaView>
  );
}

export default App;

ShopList.tsx中:

import React, { Component } from 'react';
import { View, FlatList, Image } from 'react-native';
import ShopListRow from '/Users/nb29042/Desktop/React/DemoShop/ReusableComponents/ShopListRow';
import { ListItem, Avatar } from 'react-native-elements';

interface ShopListProps {
  shops: any[];
}

class ShopList extends Component<ShopListProps> {
  render() {
    const { shops } = this.props;

    return (
      <View style={{ flex: 1, backgroundColor: '#FFFFFF' }}>
        <FlatList
          data={shops}
          renderItem={({ item, index }) => {
            return <ShopListRow shop={item} index={index} />;
          }}
          keyExtractor={(item) => item.id.toString()}
          initialNumToRender={16}
        />
      </View>
    );
  }
}

export default ShopList;
b91juud3

b91juud32#

来自https://dummyjson.com/products的响应是一个对象。

{
     products: [....]
 }

ShopList组件中,将商店的数组设置为一个对象。更新你的fetch items函数并使用products数组。

fetchItem() {
  requestAnimationFrame(() =>
    fetch(`https://dummyjson.com/products`, {
      method: 'GET',
    })
      .then(response => response.json())
      .then(responseJson => {
        this.setState({shops: responseJson.products}) // <--- here
      })
      .catch(error => {
        {
          alert(error)
        }
      }),
  );
}

相关问题