【问题标题】:maintaining couple actions in react - loading screen在反应中保持几个动作 - 加载屏幕
【发布时间】:2018-03-01 18:23:57
【问题描述】:

在我的应用程序组件中,我获取了一些东西,所以有几个动作。它是一个状态组件。当其中一项操作结束时 isLoading 属性更改为 false 并且屏幕加载消失。但它不能正常工作,因为一个动作可能比另一个动作花费更长的时间。在完成所有 async 操作后,如何将我的 isLoading 属性更改为 false?

我的代码看起来像

componentDidMount() {
  this.props.fetchA();
  this.props.fetchB();
  this.props.fetchC().then(() => {
    this.setState({isLoading: false})
  })
}

【问题讨论】:

    标签: reactjs asynchronous loading


    【解决方案1】:

    你可以像这样链接这些承诺

    componentDidMount() {
       this.setState({ isLoading: true}); // start your loader
    
       this.props.fetchA()
       .then(() => {
         return this.props.fetchB();
       })
       .then(() => {
         return this.props.fetchC()
       })
       .then(() => {
         this.setState({ isLoading: false }); // Once done, set loader to false
       })
       .catch(error => {
         console.log('Oh no, something went wrong', error);
       });
    }
    

    或者使用 async/await 和 try catch 做一些类似这样的花哨的事情。

    constructor () {
       super();
       this.state = {
         isLoading: false,
       };
       this.onLoadData = this.onLoadData.bind(this); // see what I did here, i binded it with "this"
    }
    
    componentDidMount() {
       this.onLoadData(); // Call you async method here
    }
    
    async onLoadData () {
       this.setState({ isLoading: true}); // start your loader
       try {
         const awaitA = await this.props.fetchA();
         const awaitB = await this.props.fetchB();
         const awaitC = await this.props.fetchC();
         this.setState({ isLoading: false }); // Once done, set loader to false
       } catch (e) {
         console.log('Oh no, something went wrong', error);
       }
    }
    

    【讨论】:

    • 如果这对您有帮助,请点赞此答案并将其标记为您的答案。我还添加了一种方法,如果你愿意,你可以使用 async/await 来做到这一点。
    • 带有异步的想法更干净,更漂亮!顺便说一句:我不认为你可以在构造函数之外使用 setState 方法,即使 'this' 被绑定——我说的是第一次初始化。
    • 您可以使用this.state={} 在构造函数中直接设置状态,并且您可以在代码中的任何位置使用this.setState({ }) 设置状态,除了渲染方法。您只需将this 绑定到正确的上下文即可使其正常工作。
    • 对我不起作用。说 isLoading 属性为空。不得不把它放回构造函数中。我知道它应该可以工作,因为'this'有组件上下文但是..奇怪的东西..
    • 哦,是的,你必须在构造函数中初始化它。我忘了。对不起。我更新了我的答案。道歉。现在检查 constructor() 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 2020-03-25
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多