【问题标题】:React async / await and setState not rerendering反应 async / await 和 setState 不重新渲染
【发布时间】:2018-11-03 17:30:30
【问题描述】:

从 web3 调用获得结果后,我遇到了重新渲染的问题 - 执行智能合约。代码如下:

this.setState({ loading: true });

await contractInstance.methods
                .myMethod(params)
                .send({ from: myAccount, gas: 10000000 })
                .then(async function(receipt) {
                    let txHash = receipt.transactionHash;
                    ...

                    // await saveToDb(thHash, ...)

                    this.setState({ dateToDisplay: myVar.publishDate, loading: false });

..

渲染如下:

render() {
        if (!this.state.loading) {
            return (
            ...
             {this.state.dateToDisplay}

我有其他方法可以使这种模式起作用,但在这里我无法使它起作用。我试图使 setState 异步并等待它,例如:

setStateAsync(state) {
        return new Promise(resolve => {
            this.setState(state, resolve);
        });
    }

但也无济于事。 有任何想法吗?

【问题讨论】:

    标签: javascript reactjs async-await web3


    【解决方案1】:

    你为什么把await和promise结合起来?

    await 的目的是在该点停止执行并等待 promise 解决。 const result = await promise;promise.then(result => ...) 的替代品。

    你可以这样做:

    const receipt = await contractInstance.methods
        .myMethod(params)
        .send({ from: myAccount, gas: 10000000 });
    
    let txHash = receipt.transactionHash;
    ...
    
    // await saveToDb(thHash, ...)
    
    this.setState({ dateToDisplay: myVar.publishDate, loading: false });
    

    在我看来,这使得代码不那么复杂,更容易理解正在发生的事情。

    【讨论】:

      【解决方案2】:

      您需要将 Async 函数更改为箭头函数或绑定函数,以便在该函数中可用

           await contractInstance.methods
                  .myMethod(params)
                  .send({ from: myAccount, gas: 10000000 })
                  .then(async receipt => {
                      let txHash = receipt.transactionHash;
                      ...
      
                      // await saveToDb(thHash, ...)
      
                      this.setState({ dateToDisplay: myVar.publishDate, loading: false });
      

      或者绑定一下

          await contractInstance.methods
                  .myMethod(params)
                  .send({ from: myAccount, gas: 10000000 })
                  .then(async function(receipt) {
                      let txHash = receipt.transactionHash;
                      ...
      
                      // await saveToDb(thHash, ...)
      
                      this.setState({ dateToDisplay: myVar.publishDate, loading: false });
                  }.bind(this))
      

      【讨论】:

        猜你喜欢
        • 2019-12-13
        • 2016-10-20
        • 1970-01-01
        • 1970-01-01
        • 2023-01-30
        • 2020-05-06
        • 2018-07-17
        • 1970-01-01
        • 2016-09-09
        相关资源
        最近更新 更多