React setting state with async/await

问题: So I am setting my state in my constructor with: constructor(props: IProps) { super(props); const nav = NavService.getNav(); const user = AuthService.getProfi...

问题:

So I am setting my state in my constructor with:

constructor(props: IProps) {
    super(props);
    const nav = NavService.getNav();
    const user = AuthService.getProfile();

    this.state = {
        activeNav: 0,
        nav: nav ? nav : [],
        showDropdown: false,
        showNavDropdown: false,
        user: user ? user : [],
    };
}

However, I am noticing some async issues so I want to make getNav() and getProfile() async and await them. Obviously I can't do this in the constructor because constructors cannot be async and therefore I cannot use await. Now I know I can just throw this into an async componentDidMount() but this causes a double render(). How can I optimize this?


回答1:

I think a re-render will be hard to avoid if your have to load some data asynchronously.

You could keep an additional state variable loading and just return null in the render method until your data has loaded.

Example

class App extends React.Component {
  state = {
    activeNav: 0,
    nav: [],
    showDropdown: false,
    showNavDropdown: false,
    user: [],
    loading: true
  };

  componentDidMount() {
    Promise.all(NavService.getNav(), AuthService.getProfile())
      .then(([nav, user]) => {
        this.setState({ nav, user, loading: false });
      })
      .catch(error => {
        this.setState({ loading: false });
      });
  }

  render() {
    const {
      activeNav,
      nav,
      showDropdown,
      showNavDropdown,
      user,
      loading
    } = this.state;

    if (loading) {
      return null;
    }

    // ...
  }
}
  • 发表于 2018-07-07 00:17
  • 阅读 ( 227 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除