How to render value in promises on button click in

2019-08-27 11:10发布

I have two modules

App.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import {accounts} from './contract.jsx';


class App extends React.Component{
    constructor(props){
    super(props);
    this.state={'text':'','accounts':'','clicked':false};
}
componentDidMount = () => {
    this.setState({'accounts':accounts()});
}
buttonAction = (e) => {
    this.setState({'clicked':true});
}
render(){
    return(
    <div align="center">
    <Button name="get all Accounts" action={this.buttonAction}/>
    {this.state.clicked ? <div>{this.state.accounts}</div> : null}
    </div>
    )}
}


const Button = (props) =>
    (<button onClick={props.action}>{props.name}</button>);

ReactDOM.render(<App/>,document.getElementById('root'));

and contract.jsx

import Web3 from 'web3';
var web3 = new Web3(Web3.givenProvider || 'http://localhost:8545');

let accounts = () => {
    // this is a promise
    web3.eth.getAccounts().then(function(result){console.log(result);})
    .catch(function(error){console.log(error.message)})
}
export {accounts};

I'm exporting accounts(a promise) function from contract.jsx to app.jsx. Since I can't return value from a promise, I need to assign the value to the state of App component inside the promise (check componentDidMount ). For that, I need to replace 'console.log(result)' in accounts function to 'this.setState({'accounts':result})'. But the component and accounts are in different modules and supposed to be independent. I cannot set the state of the App component inside my accounts function.

How can I assign the value from the promise to my state inside App component? Is there any other better way to do it? I could also use some code corrections to make my component work better.

1条回答
来,给爷笑一个
2楼-- · 2019-08-27 11:35

This is a little hacky, but you could try changing your constructor and render functions to:

constructor(props) {
  super(props);
  this.state = {
    'text': '',
    'accounts': null,
    'clicked': false
  };
}

...

render() {
  return(
    <div>
      { this.state['accounts'] ? (
          <div align="center">
            <Button name="get all Accounts" action={this.buttonAction}/>
            {this.state.clicked ? <div>{this.state.accounts}</div>:null}
          </div>
        ) : null 
      }
    </div>
  )
}

When the componentDidMount function does fire it should trigger a re-render. To store the value returned by the promise simply do the following in contract.jsx:

let accounts = () => {
  return web3.eth.getAccounts()
    .then( function(result) {
      return result; // Or it could be result.data, it depends
    }).catch( function(error) {
      console.error(error.message)
    });
}
查看更多
登录 后发表回答