我想在所有数据输入状态后将我的 state.loading
更改为 false
。
我想创建一个 Web 工作流程,如下所示:
state
在loading
条件设置为 true 的情况下创建- 我想使用
axios
获取 3 个 JSON 文件并将它们保存到state
中。 - 如果所有三个数据均已成功保存到
state
中,则将state.loading
更改为false
但我得到的是,在调用所有数据之前,state.loading
被声明为 false
。
代码如下:
constructor(props) {
super(props);
this.state = {
jobs : [],
category: [],
location: [],
loading : true
}
}
componentWillMount() {
window.scrollTo(0, 0);
//get any jobs available
axios.get('/thisjob/all/all').then(({data}) => this.setState({
jobs: [...data.jobs]
}));
//get any categories available
axios.get('/thiscategory').then(({data}) => this.setState({
category: [...data.category]
}));
//get any locations available
axios.get('/thislocation').then(({data}) => this.setState({
location: [...data.location]
}));
this.setState({
loading: false
})
}
这是我在 render()
中的 while console.log()
-ing 状态中找到的屏幕截图
我尝试了各种方法,从使用 if 语句到尝试将其保存到另一个生命周期方法中,但结果仍然不像我要求的工作流程。
最佳答案
您可能想要使用异步等待方法或 promise 所有方法。
一旦所有的promy都解决了,你就将State设置为loading false。
await Promise.all([someCall(), anotherCall()]);
就像有人指出的那样,在 componentDidMount 中进行提取并添加异步
async componentDidMount() {
const res = await axios.get('/thisjob/all/all');
const {ip} = await res.json(); // do other logic
const res1 = await axios.get('/thiscategory');
const {other} = await res1.json(); // do other logic
const res2 = await axios.get('/thislocation');
const {other2} = await res2.json(); // do other logic
await this.setStateAsync({loading: false})
}
关于javascript - ReactJS - 在所有数据输入状态后将我的加载更改为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54878458/