代码之家  ›  专栏  ›  技术社区  ›  Ryuujo dhara gosai

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

  •  0
  • Ryuujo dhara gosai  · 技术社区  · 6 年前

    state.loading false 在状态中输入所有数据后。

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

    1. state loading 条件设置为true
    2. 我想用 axios 并将其保存到 .
    3. 状态 ,然后改变 状态加载 错误的

    但我得到的是 状态加载 宣布 在调用所有数据之前。

    代码如下所示:

    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
        })
      }
    

    这是我在 console.log() -处于不稳定状态 render() state.loading has been declared as false before all data loaded

    1 回复  |  直到 6 年前
        1
  •  2
  •   Monica Acha    6 年前

    您可能希望使用异步等待方法或promise all。 await Promise.all([someCall(), anotherCall()]); 正如有人指出的,执行fetchincomponentdidmount并添加一个异步

    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})
      }