【问题标题】:my async functions repeats itself for unlimited times我的异步功能无限次重复
【发布时间】:2020-08-24 22:42:52
【问题描述】:

我正在使用异步函数从 API 中检索折扣,然后在购物车中使用该折扣, 每当在 render 方法中调用打折购物车功能时,它就会开始自我重复,但是当通过单击事件上的按钮执行调用时,它会完美运行。

discountedCart = async (id, qty) => {
    console.log("Discounted Cart");
    const response = await fetch(
    
      "https://usautoparts-erp.azurewebsites.net/Api/Cart",
      {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ products: [id] }),
      }
    );

    const data = await response.json();
    console.log(data);

    this.setState({
      DiscountData: data,
    });
    let D = "No discount";
    const discounts = data.filter((item) => item.quantity <= qty);
    console.log("selected");
    console.log(discounts);
    if (discounts[discounts.length - 1].amount != null) {
      D = discounts[discounts.length - 1].amount;
      console.log("Amount:" + D);
    } else if (discounts[0].percentage != null) {
      D = discounts[0].percentage;
      console.log("percentage:" + D);
    }
    console.log("Discount:" + D);
    this.setState({
      rough: D,
    });

    return D;
   
  };

render() {
   

    return (
   <>
        <Button title="Clear Cart" onPress={() => this.ClearCart()} />
       
        
        <FlatList
        
          data={this.state.p}renderItem={({ item }) => 

          {const a = this.discountedCart(item.id,item.Qty);
            return(
            <View style={{ flex: 1, flexDirection: "column", margin: 1 }}>
              <Text>{item.id}</Text>
             
              </View>
            </View>
          )}
          }
          numColumns={1}
          
          keyExtractor={item => item.id.toString()}
       
          
       
        />
     </>
    );
  }
}

【问题讨论】:

    标签: react-native async-await


    【解决方案1】:

    在这一行:

    {const a = this.discountedCart(item.id,item.Qty);
    

    您触发了 discountedCart 函数,该函数设置了导致重新渲染的状态。 当组件重新渲染时,它会调用相同的函数来设置状态 => 再次重新渲染。

    确保您没有在渲染方法中调用函数这会改变您的组件状态(或基本上使用 setstate)。

    您可能希望在 componentDidMount 上获取数据并计算折扣购物车,然后设置状态,在您的渲染方法中使用该状态属性

    【讨论】:

      猜你喜欢
      • 2013-01-23
      • 2019-05-25
      • 1970-01-01
      • 1970-01-01
      • 2019-01-01
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      相关资源
      最近更新 更多