Javascript React async/await和setState不重新提交
在从web3调用-执行智能合约得到结果后,我遇到了重新提交的问题。代码如下:Javascript React async/await和setState不重新提交,javascript,reactjs,async-await,web3,Javascript,Reactjs,Async Await,Web3,在从web3调用-执行智能合约得到结果后,我遇到了重新提交的问题。代码如下: render() { if (!this.state.loading) { return ( ... {this.state.dateToDisplay} this.setState({loading:true}); 等待constructance.methods .myMethod(参数) .send({from:myAcco
render() {
if (!this.state.loading) {
return (
...
{this.state.dateToDisplay}
this.setState({loading:true});
等待constructance.methods
.myMethod(参数)
.send({from:myAccount,gas:10000000})
.then(异步函数(接收){
设txHash=receipt.transactionHash;
...
//等待saveToDb(thHash,…)
this.setState({dateToDisplay:myVar.publishDate,load:false});
render() {
if (!this.state.loading) {
return (
...
{this.state.dateToDisplay}
渲染如下所示:
render() {
if (!this.state.loading) {
return (
...
{this.state.dateToDisplay}
我有其他方法可以使用此模式,但在这里我无法使其工作。我尝试使setState异步并等待它,如:
render() {
if (!this.state.loading) {
return (
...
{this.state.dateToDisplay}
setStateAsync(state) {
return new Promise(resolve => {
this.setState(state, resolve);
});
}
但也无济于事。
有什么想法吗?您需要将异步函数更改为arrow函数或绑定该函数,以便在该函数中可用
render() {
if (!this.state.loading) {
return (
...
{this.state.dateToDisplay}
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 });
或者把它绑起来
render() {
if (!this.state.loading) {
return (
...
{this.state.dateToDisplay}
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))
你为什么把等待和承诺结合起来
render() {
if (!this.state.loading) {
return (
...
{this.state.dateToDisplay}
await
的要点是在该点停止执行并等待承诺得到解决。const result=await promise;
是对promise的替换。然后(result=>…)
render() {
if (!this.state.loading) {
return (
...
{this.state.dateToDisplay}
您可以这样做:
render() {
if (!this.state.loading) {
return (
...
{this.state.dateToDisplay}
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 });
在我看来,这使得代码不那么复杂,更容易理解正在发生的事情并理解它
render() {
if (!this.state.loading) {
return (
...
{this.state.dateToDisplay}