![](/img/trans.png)
[英]React Native Flatlist ListHeaderComponent is not rendered on state change
[英]React Native: Flatlist rendered component state renders wrong data?
有点难以解释,所以我有这个简单的列表,
<FlatList
_light={{ bg: "gray.200" }}
_dark={{ bg: "gray.900" }}
data={data}
refreshing={isLoading}
onRefresh={loadData}
renderItem={({item})=>(
<ActivityCard
data={item}
onDeleted={()=>(console.log('delete'))}
onUpdated={()=>(console.log('updated'))}
/>
)}
ListEmptyComponent={() => {
return(
<Center flex={1} height={window.height - tabHeight*2}>
<Icon as={MaterialCommunityIcons} name='calendar-clock-outline' size={'3xl'} m={5} />
<Text>Belum ada aktivitas</Text>
</Center>
);
}}
/>
比较基础,但问题出在 ActivityCard 组件中
export default function ActivityCard({data, onUpdated, onDeleted}: prop) {
const [bid, setBid] = useState(data.BiddingPrice + data.BidMultiplier);
const [isDeleting, setIsDeleting] = useState(false);
const textColor = useColorModeValue("black", "white");
const bgColor = useColorModeValue("white", "#292524");
console.log(`${data.BiddingPrice} + ${data.BidMultiplier} = ${data.BiddingPrice + data.BidMultiplier} -- ${bid}`)
return (
<VStack flex={1} mx={4} mt={6} shadow={2} borderWidth={1} p={2} borderRadius={'md'}
_light={{ borderColor: "gray.300", bg: "gray.100" }}
_dark={{ borderColor: "gray.700", bg: "gray.700" }}
>
<HStack mt={2} space={4} height={'36px'}>
<HStack flex={1}>
<IconButton variant={'outline'} colorScheme={'purple'}
_icon={{ as: Entypo, name: "minus" }}
onPress={() => {
setBid(bid - data.BidMultiplier);
}}
/>
<MaskInput
value={bid.toString()}
keyboardType={'number-pad'}
mask={dollarMask}
style={{
flex: 1, padding: 5, textAlign: 'center', backgroundColor: bgColor, color: textColor,
borderTopColor: 'gray', borderTopWidth: 1, borderBottomColor: 'gray', borderBottomWidth: 1
}}
onChangeText={(masked, unmasked) => {
setBid(parseInt(unmasked));
}}
/>
<IconButton variant={'outline'} colorScheme={'purple'}
_icon={{ as: Entypo, name: "plus" }}
onPress={() => {
setBid(bid + data.BidMultiplier);
}}
/>
</HStack>
<Button flex={1/4} size={'xs'}
onPress={() => {
(async () => {
const {data: resp} = await api.addBid(data.ID, bid);
console.log(resp);
})();
}}
>
BID
</Button>
</HStack>
</VStack>
)
};
我已经将 state 设置为 price to bid + multiplier,但几行后该值是错误的。 控制台日志结果:
LOG 100000 + 10000 = 110000 -- 43000
LOG 200000 + 10000 = 210000 -- 130000
LOG 43000 + 3000 = 46000 -- 15000
LOG 120000 + 10000 = 130000 -- 130000
LOG 12500 + 2500 = 15000 -- 130000
LOG 125000 + 5000 = 130000 -- 130000
LOG 125000 + 5000 = 130000 -- 130000
我如何解决这个问题 go? 我可以在 Flatlist 的行中使用状态吗?
ooof想通了。 好像我不能只在初始化期间设置值,所以const [bid, setBid] = useState(data.BiddingPrice + data.BidMultiplier);
不好。
需要在useEffect
中设置它,比如:
const [bid, setBid] = useState(0);
useEffect(() => {
setBid(data.BiddingPrice + data.BidMultiplier);
}, []);
一切都会按预期进行。 所有的值都是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.