React async / await 和 setState 不重新渲染

React async / await and setState not rerendering

我在从 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);
        });
    }

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

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

     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))

为什么要结合 await 和 promises?

await 的要点是在那一点停止执行并等待承诺解决。 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 });

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