Is it possible to use async / await in React JS?

前端 未结 3 1503
盖世英雄少女心
盖世英雄少女心 2020-12-13 17:34

I started programming in React Native, and I got used to use the syntax:

async myFunction(){
    ...
    return await otherFunction();
}

Bu

相关标签:
3条回答
  • 2020-12-13 18:27

    If you building using create-react-app it's been available since v0.2.3

    https://github.com/facebookincubator/create-react-app/releases/tag/v0.2.3

    It can be used inside a Component like this

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = { message: '' };
      }
    
      async componentDidMount() {
        this.setState({ message: 'loading...' });
        let d = await getData('/posts/1');
        this.setState({ message: d });
      }
    
      render() {
        let { message } = this.state;
        return (
          <div className="App">
            <p className="App-intro">
              { message }
            </p>
          </div>
        );
      }
    }
    

    See:

    https://github.com/facebookincubator/create-react-app/issues/1024

    0 讨论(0)
  • 2020-12-13 18:32

    React Native ships with Babel and some Babel presets, whereas React on the web is just React related code.

    If you want to use async/await on the web today you'll need Babel and the correct transforms: https://babeljs.io/docs/plugins/transform-async-to-generator/

    or the stage-1 presets, which is fairly common in React apps today. http://babeljs.io/docs/plugins/preset-stage-1/

    0 讨论(0)
  • 2020-12-13 18:32

    Alternatively you can use Typescript.

    Since version 2.1 it is possible to use async/await and directly transpile to ES5 (in other words have it run on ~all browsers)

    0 讨论(0)
提交回复
热议问题