【问题标题】:React native does not wait for the function to finishReact Native 不等待函数完成
【发布时间】:2021-01-03 18:09:55
【问题描述】:
      Listele = async () => {
    try {
      const response = await fetch('http://192.168.1.114/reactapp/Userpage.php', {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
      } 
      })
      responseData = await response.json()
      global.data= {veri:responseData}
      global.justClicked = 0
    }
    catch (error) {
      console.error(error);
    }
  };
  
  render() {

    this.Listele();
    var cardLists=[]; 
    for(let i = 1; i <= global.data.veri[0]; i++) 
    {
      cardLists.push(
        <ListCard key={i} onPress={() => {this.setModalVisible(true);global.justModal=i;}}/>
      )
    }
    const { modalVisible } = this.state;
    return ( ........

For 循环不起作用“未定义不是一个对象 global.data.veri”。重新加载几次后,它可以工作,但我意识到该功能没有等待。我该如何解决?

【问题讨论】:

    标签: reactjs asynchronous async-await


    【解决方案1】:

    从渲染中删除循环遍历代码并为其创建单独的方法

     addCartItems(){
      var cardLists=[]; 
        for(let i = 1; i <= global.data.veri[0]; i++) 
        {
          cardLists.push(
            <ListCard key={i} onPress={() => {this.setModalVisible(true);global.justModal=i;}}/>
          )
        }
      }
    
    Listele = async () => {
      try {
        const response = await fetch("http://192.168.1.114/reactapp/Userpage.php", {
          method: "GET",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
          },
        });
        responseData = await response.json();
        global.data = { veri: responseData };
        this.addCartItems(); // add this
        global.justClicked = 0;
      } catch (error) {
        console.error(error);
      }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-14
      • 1970-01-01
      • 2019-06-16
      • 2020-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多