我在平面列表中遇到了一个问题,即如果我在增加值后不刷新或点击ctrl-s,按钮会增加值,但不会显示基本上,如果不按ctrl-s或转到另一页并返回到同一页,我就无法看到值的变化
<FlatList
data={store}
renderItem={({ item }) => {
return (
<View style={styles.itemCountView}>
<TouchableOpacity style={styles.up}
onPress={() => item.itemCount++}>
<MaterialIcons name="arrow-drop-up" size={36} color="#ddd"/>
</TouchableOpacity>
<Text style={styles.itemCountText}>{item.itemCount}</Text>
</View>
)
}}
/>
我可以增加值,如果我保存或转到另一个页面,然后返回值更改,我可以看到它,但必须有一种方法可以看到它更改。
感谢任何帮助
根据文档
extraData:https://reactnative.dev/docs/flatlist#extradata
一个标记属性,用于告诉列表重新渲染(因为它实现了PureComponent(。如果您的renderItem、Header、Footer等函数中的任何一个依赖于数据道具之外的任何东西,请将其粘贴在此处并进行免疫处理。
我认为你没有保存你所做的更改,基本上你需要在每次增加一个项目时更新store
变量,比如:
<FlatList
data={store}
renderItem={({ item }) => {
return (
<View style={styles.itemCountView}>
<TouchableOpacity style={styles.up}
onPress={() => {
const newStoreData = [...store]
const itemIndex = newStoreData.findIndex(item)
const newItem = {...item,itemCount:item.itemCount ++}
newStoreData[itemIndex] = newItem
setStoreData(newStoreData) // state or redux?
}
}>
<MaterialIcons name="arrow-drop-up" size={36} color="#ddd"/>
</TouchableOpacity>
<Text style={styles.itemCountText}>{item.itemCount}</Text>
</View>
)
}}
/>
您可以在这里尝试这种方法:
import {useState} from 'react';
import { Text, View, FlatList, TouchableOpacity } from 'react-native';
const store = [{
itemCount: 1
},
{
itemCount: 2
},
{
itemCount: 3
}]
export default function App() {
return (
<View style={{
flex: 1,
padding: 140,
}}>
<FlatList
data={store}
renderItem={({ item }) => ( <Item item={item}/> )}
/>
</View>
);
}
const Item = ({item})=> {
const[count, setCount] = useState(item.itemCount);
return (
<View>
<TouchableOpacity
style={{
backgroundColor: 'black',
padding: 10,
margin: 10
}}
onPress={() => setCount(count+1)}>
<Text style={{
color: 'white'
}}>{count}</Text>
</TouchableOpacity>
</View>
)
}
这将设置平面列表中每个项目的状态。