简体   繁体   English

有没有办法将 state 信息从反应挂钩传递到反应中的嵌套函数?

[英]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.我正在尝试找到一种将 {account} 和 {value} 放入 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.我尝试了不同的方法,例如将 {account} 和 {value} 传递为 arguments (即 handlePledge({account}, {value})),但没有运气。

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.您可以并且应该直接使用任何 state 变量。

    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.正如@Nick 暗示的那样,您实际上可以在封闭的 scope 中使用这些变量。 They are perfectly accessible from functions you declare within their shared scope.它们可以从您在共享 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.如果我没有回答您的问题,请说明您遇到的确切错误。

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

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