簡體   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