【问题标题】:re-render in react native- issue在反应本机问题中重新渲染
【发布时间】:2018-05-14 11:14:33
【问题描述】:

如果用户单击“是”从列表中删除该项目,我在本机反应中有此代码。但是物品还在包里,直到刷新它! 单击删除时如何重新渲染?

  const bagProducts = this.props.allProducts;
    const productId = this.props.deleteProductAction(this.props.id).id;
    var result = bagProducts.filter(x => {
      return x.id == productId;
    })[0];

  <TouchableOpacity
            style={styles.bagItemButtons}
            onPress={() => {
              Alert.alert(
                "Alert",
                "Are you sure wnat do delete ?",
                [
                  { text: "NO", onPress: () => console.log("Cancel pressed") },
                  {
                    text: "Yes",
                    onPress: () => {
                      bagProducts.splice(result, 1);
                    }
                  }
                ],
                { cancelable: true }
              );
            }}
          >
            <Text style={styles.bagItemButtonText}>{t("delete")}</Text>
          </TouchableOpacity>

【问题讨论】:

    标签: javascript reactjs react-native rendering


    【解决方案1】:

    将您的列表项放入状态并更新它将呈现列表的状态

    【讨论】:

      【解决方案2】:

      您的 bagProducts 应该保存在本地状态,然后您运行 setState 来修改 bagProducts。这将导致重新渲染。

      【讨论】:

      • const bagProducts = this.props.allProducts;我的 bagProducts 是我从中删除项目的对象数组
      【解决方案3】:

      我不知道你是如何渲染bagProducts的。

      但是如果你想重新渲染包,你需要更新状态。

      假设state 对象。

      添加事件处理程序以更新包,

      updateBags=()=>{
      
          bagProducts.splice(result, 1);
      
          this.setState(({bagProducts}));
      }
      

      在 onPress 上致电 updateBags

      onPress: this.updateBags //onPress should be like this.call updateBags
      

      【讨论】:

      • bagProduts 我将从中删除的对象大军。 const bagProducts = this.props.allProducts;常量 productId = this.props.deleteProductAction(this.props.id).id; var result = bagProducts.filter(x => { return x.id == productId; })[0];
      【解决方案4】:

      你可以使用

              this.forceUpdate()
      

      删除函数末尾的方法。

      【讨论】:

      • 这太恶心了。它会起作用,但是如果你使用 forceUpdate() 那么你就错过了反应点。
      • 是的,但是我已经有一个错误告诉我由于状态改变而无法渲染
      猜你喜欢
      • 2016-07-13
      • 2021-02-09
      • 2019-02-16
      • 2022-06-15
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多