简体   繁体   中英

Is there a way of passing state information from react hooks into nested functions in react?

This is my first solo react project so apologies if I've missed anything glaring. I am trying to find a way to get the {account} and {value} into handlePledge. Obviously you can't use them directly in nested functions. I have tried different things such as passing {account} and {value} as arguments (ie handlePledge({account}, {value})) but no luck.

function App() {
  const [account, setAccount] = useState();
  const [button, setButton] = useState('Enable Ethereum');
  const [value, setValue] = useState(1);


  const handlePledge = async (e) => {
    e.preventDefault();
    const gas = await SixtySixDays.methods.createNewPledge().estimateGas();
    const result = await SixtySixDays.methods.createNewPledge().send({
      from: #account-goes-here,
      gas,
      value: #value-goes-here
    })
    console.log(result);
  }

Thank you, any help is greatly appreciated.

You can pass the values directly like this:

 const result = await SixtySixDays.methods.createNewPledge().send({
   from: account,
   gas,
   value: value
}

"Obviously you can't use them directly in nested functions." - You can and you should

You can and should use the any state variables directly.

    const result = await SixtySixDays.methods.createNewPledge().send({
      from: account,
      gas,
      value: value
    })

The above should work.

As @Nick implies, you in fact can use those variables in an enclosed scope. They are perfectly accessible from functions you declare within their shared scope.

Perhaps your issue is how the rendering is being updated? If I've not answered your issue, please kindly show the exact error you're getting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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