FlatList 在 React Native 中未显示结果。

huangapple go评论93阅读模式
英文:

FlatList not shown result in React native

问题

I can provide a translation of your code without addressing the issue you mentioned. Here is the translated code:

我是React Native的新手我正在尝试创建一个简单的FlatList并从Api https://dummyjson.com/products 填充它,但它从未显示结果...
以下是我的App.tsx代码

```javascript
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())
    .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;

以下是ShopList代码

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 })
        })
        .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'

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没有显示任何结果,我将不胜感激...
最好的问候。

英文:

I am new to React native and i am trying to create a simple flatlist and fill it from Api https://dummyjson.com/products but it never show results ...
here is my App.tsx code

import React from &#39;react&#39;;
import type {PropsWithChildren} from &#39;react&#39;;
import {
FlatList,
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
} from &#39;react-native&#39;;
import ShopList from &#39;./ReusableComponents/ShopList&#39;;
import axios from &#39;axios&#39;;
import {
Colors,
DebugInstructions,
Header,
LearnMoreLinks,
ReloadInstructions,
} from &#39;react-native/Libraries/NewAppScreen&#39;;
type SectionProps = PropsWithChildren&lt;{
title: string;
}&gt;;
function App(): JSX.Element {
const isDarkMode = useColorScheme() === &#39;dark&#39;;
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
const shops: ArrayLike&lt;any&gt; | null | undefined = []
fetch(&#39;https://dummyjson.com/products&#39;)
.then(response =&gt; response.json())//hat el jsonresponse law rege3
.then(result =&gt; { shops })
console.log({shops})
return (
&lt;SafeAreaView style={backgroundStyle}&gt;
&lt;StatusBar
barStyle={isDarkMode ? &#39;light-content&#39; : &#39;dark-content&#39;}
backgroundColor={backgroundStyle.backgroundColor}
/&gt;
&lt;ShopList /&gt;
&lt;/SafeAreaView&gt;
);
}
const styles = StyleSheet.create({
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: &#39;600&#39;,
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: &#39;400&#39;,
},
highlight: {
fontWeight: &#39;700&#39;,
},
edges: {
flex: 1,
alignItems: &#39;center&#39;,
justifyContent: &#39;center&#39;,
padding: 5,
minWidth: 50
}
});
export default App;

And here is ShopList code

import React, {Component} from &#39;react&#39;;
import {
View,
FlatList,
Image
} from &#39;react-native&#39;
import ShopListRow from &#39;/Users/nb29042/Desktop/React/DemoShop/ReusableComponents/ShopListRow&#39;;
import { ListItem, Avatar } from &#39;react-native-elements&#39;;
export default class ShopList extends Component {
constructor(props){
super(props);
this.state = {
shops: []
}
}
fetchItem() {
requestAnimationFrame(() =&gt;
fetch(`https://dummyjson.com/products`, {
method: &#39;GET&#39;,
})
.then(response =&gt; response.json())
.then(responseJson =&gt; {
this.setState({shops: responseJson})
// console.warn(this.state.shops);
})
.catch(error =&gt; {
{
alert(error)
}
}),
);
}
componentDidMount(){
this.fetchItem()
}
render() {
return (
&lt;View style={{
flex: 1,
backgroundColor: &#39;#FFFFFF&#39;
}}&gt;
&lt;FlatList
data = {
this.state.shops
}
renderItem={({ item, index }) =&gt; 
{
return &lt;ShopListRow 
shop={item} 
index={index} 
/&gt;}
}
keyExtractor={item =&gt; item.id}
initialNumToRender={16}
extraData={this.state}
/&gt;
&lt;/View&gt;
);
}
}

And the ShopListRow Code is:

import React, {Component} from &#39;react&#39;;
import {
View,
Text,
StyleSheet,
TextInput,
TouchableHighlight,
FlatList,
Image
} from &#39;react-native&#39;
//import Stars from &#39;./Stars&#39;;
export default class ShopListRow extends Component {
render() {
const {
shop,
index
} = this.props
return (
&lt;View key={shop.id} style={{ backgroundColor: index % 2 === 0 ? &#39;white&#39; : &#39;#F3F3F7&#39; }}&gt;
&lt;View style={styles.row}&gt;
&lt;View &gt;
&lt;Text&gt;{shop.title}&lt;/Text&gt;
&lt;Text &gt;{shop.description}&lt;/Text&gt;
&lt;/View&gt;
&lt;View style={styles.edges}&gt;
&lt;TouchableHighlight 
//onPress={this.infoPressed}
style={styles.button}
underlayColor=&#39;#5398DC&#39;
&gt;
&lt;Text style={styles.buttonText}&gt;Info&lt;/Text&gt;
&lt;/TouchableHighlight&gt;
&lt;/View&gt;
&lt;/View&gt;
&lt;/View&gt;
)
}
}
const styles = StyleSheet.create({
row: {
flexDirection: &#39;row&#39;
},
edges: {
flex: 1,
alignItems: &#39;center&#39;,
justifyContent: &#39;center&#39;,
padding: 5,
minWidth: 50
},
stars: {
flex: 1,
alignItems: &#39;center&#39;,
flexDirection: &#39;row&#39;,
justifyContent: &#39;flex-start&#39;,
padding: 5,
minWidth: 50
},
nameAddress: {
flexDirection: &#39;column&#39;,
flex: 8,
padding: 5
},
addressText: {
color: &#39;grey&#39;
},
button: {
borderWidth: 1,
borderColor: &#39;#0066CC&#39;,
borderRadius: 14,
paddingHorizontal: 10,
paddingVertical: 3,
backgroundColor: &#39;#fff&#39;,
},
buttonText: {
color: &#39;#0066CC&#39;,
fontSize: 12
},
info: {
marginHorizontal: 40,
marginVertical: 10,
padding: 10,
backgroundColor: &#39;#fff&#39;,
borderWidth: 1,
borderColor: &#39;#ddd&#39;,
borderRadius: 4
}
})

if anyone can help me why flatlist results not shown any results i will be thankful...
best regards

答案1

得分: 0

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

{
     products: [....]
 }

在你的 ShopList 组件中,你将商店的数组设置为一个对象。更新你的获取物品函数,使用产品数组。

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

The response from https://dummyjson.com/products is an object.

{
products: [....]
}

In your ShopList component, you're setting the shop's array to an object. Update your fetch items function and use the products array.

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

huangapple
  • 本文由 发表于 2023年5月28日 21:27:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76351737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定