繁体   English   中英

如何从反应上下文更新反应组件

[英]How to update React Components from react context

如何在反应上下文中增加计数,因为我需要根据 ContextCount.js 文件上发生的一些事件更改计数值

let count = 0;

 const createSale = async (url, formInputPrice, isReselling, id) => {
    // connect to smart contract

    const web3Modal = new Web3Modal();
    const connection = await web3Modal.connect();
    const provider = new ethers.providers.Web3Provider(connection);
    const signer = provider.getSigner();
    // value of wei of zeo of to convert to it that what metamask read
    const price = ethers.utils.parseUnits(formInputPrice, 'ether');
    // calling func() from contract takes time so use await
    const contract = fetchContract(signer);
    count += 1;
    const listingPrice = await contract.getListingPrice();
    const transaction = !isReselling
      ? await contract.createToken(url, price, { value: listingPrice.toString() })
      // else it belong to this
      : await contract.resellToken(id, price, { value: listingPrice.toString() });
    await transaction.wait();
  };
 <NFTContext.Provider value={{ count }}>
      {children}
    </NFTContext.Provider>

在 React Components 文件夹上,当发生 createale function 时,我需要传递更新的计数值

所以我在 components 文件夹上使用我创建了一个 countupdate.jsx 在那里 import React from 'react'; 我导入了上下文文件然后我使用

 const { count } = useContext(ContextCount);
const updateIt = () => (
  <div>{count}</div>
);

导出默认updateIt;

所以我需要显示从 ContextCount.js 到组件文件 updateIt.jsx 的更新值有谁知道如何实现这个?

它没有更新,因为您使用了错误的钩子。 在这里您可以了解有关hooks的所有信息。 上下文挂钩应该在组件内部使用,如下所示:

const updateIt = () => {
  const { count } = useContext(ContextCount);
  return (
    <div>{count}</div>
  );
};

这是关于如何从消费者那里更新上下文数据的答案

暂无
暂无

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

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