简体   繁体   English

React Native:Flatlist 渲染组件 state 渲染了错误的数据?

[英]React Native: Flatlist rendered component state renders wrong data?

A bit hard to explain, so I have this flat list,有点难以解释,所以我有这个简单的列表,

      <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>
          );
        }}
      />

Relatively basic, but the issue is in the ActivityCard component比较基础,但问题出在 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>
  )
};

I've set the state to price to bid + multiplier, but the value is wrong after a few rows.我已经将 state 设置为 price to bid + multiplier,但几行后该值是错误的。 The console log result:控制台日志结果:

 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

How do I go about fixing this?我如何解决这个问题 go? Can I use states within rows of Flatlist?我可以在 Flatlist 的行中使用状态吗?

Ooof figured it out. ooof想通了。 Seems like I can't just set the value during initialization, so const [bid, setBid] = useState(data.BiddingPrice + data.BidMultiplier);好像我不能只在初始化期间设置值,所以const [bid, setBid] = useState(data.BiddingPrice + data.BidMultiplier); is bad.不好。

Need to set it up within useEffect , so something like:需要在useEffect中设置它,比如:

const [bid, setBid] = useState(0);

useEffect(() => {
  setBid(data.BiddingPrice + data.BidMultiplier);
}, []);

And everything will work as expected.一切都会按预期进行。 All the values are correct.所有的值都是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM