数据在FlatList中没有显示。

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

Data is not being displayed in in FlatList

问题

我在React中显示一些数据。我从localStorage中读取这些数据并在FlatList中显示。数据存在于数组中,但没有显示出来。

cartItems 是包含这些数据的数组,并将该数组传递给FlatList。

cartItems = [
  {"food": "bread", "foodPrice": "Rs. 100"},
  {"food": "bread", "foodPrice": "Rs. 100"},
  {"food": "bread", "foodPrice": "Rs. 100"},
  {"food": "bread", "foodPrice": "Rs. 100"},
  {"food": "bread", "foodPrice": "Rs. 100"}
]

但没有数据显示出来。

Cart.js:

import React from "react";
import {
    StyleSheet,
    FlatList,
    View,
    Image,
    TouchableOpacity,
    Text
} from "react-native";

export default class Cart extends React.Component {
    constructor() {
        super();
        this.state = {
            cartItems: []            
        };

        let orderArray = localStorage.getItem("Foods") // 获取先前存储的食品项目
        
        let cartItems = []
        if (orderArray !== null) {
            //cartItems = [...JSON.parse(orderArray)]
            this.setState({cartItems: [...JSON.parse(orderArray)]})
        }
        
        console.log("Cart: cartItems = "+JSON.stringify(cartItems));
    }

    renderItemComponent = (data) =>
        <TouchableOpacity style={styles.container}>
            <Image style={styles.image} source={{ uri: data.item.url }} />
        </TouchableOpacity>

    ItemSeparator = () => <View style={{
        height: 2,
        backgroundColor: "rgba(0,0,0,0.5)",
        marginLeft: 10,
        marginRight: 10,
    }}
    />

    render() {
        return (
            <View>
                <FlatList
                    data={this.state.cartItems}
                    renderItem={({ item }) =>
                        <TouchableOpacity >
                            <Text >{item.food}</Text>
                            <Text >{item.foodPrice}</Text>
                        </TouchableOpacity>
                    }
                    ItemSeparatorComponent={this.ItemSeparator}
                />
            </View>
        )     
    }
}

const styles = StyleSheet.create({
    container: {
        height: 300,
        margin: 10,
        backgroundColor: '#FFF',
        borderRadius: 6,
    },
    image: {
        height: '100%',
        borderRadius: 4,
    },
});

这个问题的根本原因是什么呢?看起来是一个很小的问题,但目前还找不到。

英文:

I am displaying some data in React. I read this data from localStorage and display in FlatList.
Data is there in array, but not getting displayed.

cartItems is the array which have this data and this array is passed to FlatList.

cartItems = [{&quot;food&quot;:&quot;bread&quot;,&quot;foodPrice&quot;:&quot;Rs. 100&quot;},{&quot;food&quot;:&quot;bread&quot;,&quot;foodPrice&quot;:&quot;Rs. 100&quot;}, 
{&quot;food&quot;:&quot;bread&quot;,&quot;foodPrice&quot;:&quot;Rs. 100&quot;},{&quot;food&quot;:&quot;bread&quot;,&quot;foodPrice&quot;:&quot;Rs. 100&quot;}, 
{&quot;food&quot;:&quot;bread&quot;,&quot;foodPrice&quot;:&quot;Rs. 100&quot;}]

But no data is being displayed.

Cart.js:

import React from &quot;react&quot;;
import {
StyleSheet,
FlatList,
View,
Image,
TouchableOpacity,
Text
} from &quot;react-native&quot;;
export default class Cart extends React.Component {
constructor() {
super();
this.state = {
cartItems: []            
};
let orderArray = localStorage.getItem(&quot;Foods&quot;) // Get previously stored food items
let cartItems = []
if (orderArray !== null) {
//cartItems = [...JSON.parse(orderArray)]
this.setState({cartItems: [...JSON.parse(orderArray)]})
}
console.log(&quot;Cart: cartItems = &quot;+JSON.stringify(cartItems));
}
renderItemComponent = (data) =&gt;
&lt;TouchableOpacity style={styles.container}&gt;
&lt;Image style={styles.image} source={{ uri: data.item.url }} /&gt;
&lt;/TouchableOpacity&gt;
ItemSeparator = () =&gt; &lt;View style={{
height: 2,
backgroundColor: &quot;rgba(0,0,0,0.5)&quot;,
marginLeft: 10,
marginRight: 10,
}}
/&gt;
render() {
return (
&lt;View&gt;
&lt;FlatList
data={this.state.cartItems}
renderItem={({ item }) =&gt;
&lt;TouchableOpacity &gt;
&lt;Text &gt;{item.food}&lt;/Text&gt;
&lt;Text &gt;{item.foodPrice}&lt;/Text&gt;
&lt;/TouchableOpacity&gt;
}
ItemSeparatorComponent={this.ItemSeparator}
/&gt;
&lt;/View&gt;)     
}
}
const styles = StyleSheet.create({
container: {
height: 300,
margin: 10,
backgroundColor: &#39;#FFF&#39;,
borderRadius: 6,
},
image: {
height: &#39;100%&#39;,
borderRadius: 4,
},
});

What can be the root cause of this problem.
It seems that, there is very small issue, but not able to find yet.

答案1

得分: 3

你的组件在设置cartItems之后没有重新渲染:

cartItems = [...JSON.parse(orderArray)]

它从初始状态将cartItems视为空数组并未显示任何数据,所以你应该使用this.setState来重新渲染组件,正确的方式应该是这样的:

this.setState({cartItems: [...JSON.parse(orderArray)]})

更新:

  • 现在你已经正确设置了数据,
  • 但在设置数据时时间点很重要。

如果你的数据最初来自本地存储,那么你的代码就可以正常工作,但如果最初本地存储中没有数据,那么你需要根据你的应用场景(工作逻辑)正确使用componentDidMount()componentDidUpdate()来设置它们。

这样,本地存储中数据的更新才会反映在你的组件中。

你也可以在这里阅读更多详细信息:https://reactjs.org/docs/react-component.html

还要检查组件生命周期

英文:

Your component is not re-rendering after cartItems is set like this :

cartItems = [...JSON.parse(orderArray)]

It is taking cartItems as an empty array from initial state and showing no data, so you should use this.setState to re-render the component, the correct way would be like this :

this.setState({cartItems: [...JSON.parse(orderArray)]})

Update :

  • now you are setting the data correctly,
  • but when you are setting the
    data is important.

if your data is available from local storage initially then it will work for your code, but if the data is not available initially in local storage, then you need to set them correctly using

componentDidMount() or componentDidUpdate() depending on your app scenario (working logic).

then only the data in local storage updation will reflect in you component.

you can also read more details here: https://reactjs.org/docs/react-component.html

also check The Component Lifecycle

huangapple
  • 本文由 发表于 2023年2月8日 11:54:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75381225.html
匿名

发表评论

匿名网友

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

确定