javascript - ReactJS - 在所有数据输入状态后将我的加载更改为 false

标签 javascript reactjs

我想在所有数据输入状态后将我的 state.loading 更改为 false

我想创建一个 Web 工作流程,如下所示:

  1. stateloading 条件设置为 true 的情况下创建
  2. 我想使用 axios 获取 3 个 JSON 文件并将它们保存到 state 中。
  3. 如果所有三个数据均已成功保存到 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 状态中找到的屏幕截图 state.loading has been declared as false before all data loaded

我尝试了各种方法,从使用 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/

相关文章:

javascript - 三.js球坐标公式

javascript - Codewars Javascript 问题 - 我的带有双 for 循环的代码超时

javascript - Javascript 中如何创建、合并和销毁 xmlhttprequest 对象

reactjs - 清理本地存储后如何进行重定向?

reactjs - 为什么需要 ParentComponent.childContextTypes 和 ChildComponent.contextTypes?

javascript - 下拉列表中的自动建议

javascript - Cypress ,如果其他/切换案例不起作用

javascript - 如何使用 jest 测试 React 组件?

reactjs - Jest 文件夹结构

javascript - 大 React 类还是外部 Controller ?