【问题标题】:如何在链函数中调用外部函数?
【发布时间】:2022-01-21 18:48:49
【问题描述】:

这是一个关于 React 和 Dapp 的案例。

我调用 web3j 来 sendTransaction 并通过 chian 函数等待回调。 发生错误时,我无法调用 App 内的函数。

我在错误块周围的代码中描述了以下情况。

是否可以调用函数handleError?

//My code
class App extends Component {
    constructor(props) {
        super(props);
            this.state = {
            status: ''
            };
    };
    
    startTrade(){
        web3.eth.sendTransaction({
            from: "0x123....",
            to: "0x456....", 
            value: web3.utils.toWei("2", "ether"),
        }).on('error', (error)=>{
            
            //If write this line,the browser shows directly:
            //Failed to compile
            //src\App.js
            //Line 62:7:  'handleFail' is not defined  no-undef     
            
            //handleError(); 
            
            //If add this. when error occurs,the console shows:
            //App.js:62 Uncaught TypeError: Cannot read properties of undefined (reading 'handleFail')
            
            //this.handleFail();

            //If I call otherHandle,It's work.
            //However I don't have the instance of App to change something...
            //otherHandle();
        }); 
    }
    handleError(){
       console.log("Do something..");
    }
    render(){ return();
    }
}
function otherHandle(){
    console.log("Do something..");
}

【问题讨论】:

  • 是的,可以在错误块内调用函数。你得到什么错误?
  • 嗨~我已经把它写到了错误块周围的源代码注释中。

标签: javascript reactjs web3js


【解决方案1】:
export default function App() {
  const handleError = (error) => {
    console.log("Do something..", error.message);
 }

  const startTrade = ()=>{
    web3.eth.sendTransaction({
        from: "0x0Cb......",
        to: "0x61d63........", 
        value: web3.utils.toWei("2", "ether"),
    }).on('error', (error)=>{
        handleError(error); 
    }); 
}

    // useEffect Function...
    useEffect(() => {
      startTrade();
      // eslint-disable-next-line 
  }, []);

  return (
    <div className="App">
    </div>
  );
}

【讨论】:

  • 谢谢.. 但是我的渲染/返回有状态要显示,我需要有构造函数(props)语句来设置 this.state ,所以我不能使用你的示例代码。
  • 你可以在 hooks 的帮助下轻松使用它,也可以将 props 传递到任何你想要的地方
  • 太好了~非常感谢!你的提示完美解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-21
  • 2017-02-01
  • 2018-05-27
  • 1970-01-01
相关资源
最近更新 更多