在反应 - 加载屏幕中保持夫妇行动
maintaining couple actions in react - loading screen
在我的应用程序组件中,我正在获取一些东西,所以有一些动作。它是一个状态组件。当其中一项操作结束时,isLoading
属性 变为 false,屏幕加载消失。但它不能正常工作,因为一个动作可能比另一个动作花费更长的时间。在完成所有 async
操作后,如何将我的 isLoading
属性 更改为 false?
我的代码看起来像
componentDidMount() {
this.props.fetchA();
this.props.fetchB();
this.props.fetchC().then(() => {
this.setState({isLoading: false})
})
}
您可以像这样链接这些承诺
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);
}
}
在我的应用程序组件中,我正在获取一些东西,所以有一些动作。它是一个状态组件。当其中一项操作结束时,isLoading
属性 变为 false,屏幕加载消失。但它不能正常工作,因为一个动作可能比另一个动作花费更长的时间。在完成所有 async
操作后,如何将我的 isLoading
属性 更改为 false?
我的代码看起来像
componentDidMount() {
this.props.fetchA();
this.props.fetchB();
this.props.fetchC().then(() => {
this.setState({isLoading: false})
})
}
您可以像这样链接这些承诺
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);
}
}