简体   繁体   English

更改 UseState Hook React 组件后不会重新渲染

[英]After changing a UseState Hook React component is not re-rendering

I read many topics around these problem but none of them helped to find an answer.我阅读了很多关于这些问题的主题,但没有一个有助于找到答案。

I am using a useEffect to fetch an array of objects "nftRewards".我正在使用 useEffect 来获取对象数组“nftRewards”。 And it's working fine cause I can see them on the console.而且它工作正常,因为我可以在控制台上看到它们。 But the part of the render that depends on this hook is not re-render once it was updated.但是依赖于这个钩子的渲染部分一旦更新就不会重新渲染。 And I don't understand why.我不明白为什么。

  const [campaignRewardsJson, setCampaignRewardsJson] = useState<nftReward[]>([]);

  const { data: rewards } = useContractRead({
    address: campaignsId,
    abi: campaignABI,
    functionName: 'getRewards',
  });

  async function getRewardObject() {
    var array: nftReward[] = [];
    rewards.map(async (reward, index) => {
      const json = fetch(reward[2]);
      const data = await json.then((res) => res.json());

      const nft: nftReward = {
        title: data.name,
        description: data.description,
        imageURL: data.image,
        price: reward[0],
        quantity: reward[1],
      };

      array.push(nft);
    });
    return array;
  }

  type nftReward = {
    title: string;
    description: string;
    imageURL: string;
    price: number;
    quantity: number;
  };


  useEffect(() => {
    if (rewards) {
      const fetchData = async () => {
        var data = await getRewardObject();

        setCampaignRewardsJson(data);
      };
      // call the function
      fetchData().catch(console.error);
    }
  }, [rewards]);

And At the end of my render, I have this but It's never render by react:在我的渲染结束时,我有这个但它永远不会通过反应渲染:

{campaignRewardsJson.map((reward, index) => (
            <Card direction={{ base: 'column', sm: 'row' }} overflow="hidden" variant="outline">
              <Image objectFit="cover" maxW={{ base: '100%', sm: '200px' }} src={reward.imageURL} alt="Caffe Latte" />

              <Stack>
                <CardBody>
                  <Heading size="md">{reward.title}</Heading>
                  <Text py="2">{reward.description}</Text>
                </CardBody>

                <CardFooter>
                  <Button variant="solid" colorScheme="blue">
                    Mint NFT
                  </Button>
                </CardFooter>
              </Stack>
            </Card>
          ))}

If rewards is state in this component and type of that is object or array.如果此组件中的 rewards 为rewards ,则其类型为 object 或数组。 When you pass array or object to dependency, every render snapshot will compare with previous version.当您将数组或 object 传递给依赖项时,每个渲染快照都会与以前的版本进行比较。 You may try keyword useEffect dependency array and object comparison .你可以试试关键字useEffect dependency array and object comparison for more information.想要查询更多的信息。

Try this:尝试这个:

useEffect(() => {
  if (rewards) {
    const fetchData = async () => await getRewardObject();

    // call the function
    fetchData()
      .then(data => setCampaignRewardsJson(data))
      .catch(console.error);
    }
 }, [rewards]);

your useEffect hook has rewards as its dependencies.您的 useEffect 挂钩将rewards作为其依赖项。 and it will only run if rewards is true or it's defined and not null(truthy).并且它只会在rewards为真或已定义且不为空(真实)时运行。 you need to check that condition.你需要检查那个条件。

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

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