setState不会更新React Native

时间:2018-08-14 00:41:32

标签: javascript reactjs react-native

我有一个具有以下功能的React Native应用程序:

delete(index){
        this.setState({deletedIndex:index, cachedCart:this.state.Cart, Cart: this.state.Cart.splice(index,1) },
            function(){
                console.log(this.state.cachedCart);
                Toast.show({
                text: 'Item deleted from Cart',
                position: 'bottom',
                buttonText: 'Undo',
                duration: 2000,
                onClose: this.undoDelete.bind(this)
            });
        });

    }

我的问题是,如果我还要更新购物车的状态,则deleteIndex和cachedCart不会更新。但是,如果删除Cart: this.state.Cart.splice(index,1),一切正常。我已经尝试过使用DeletedIndex和cachedCart的硬编码值,但也不起作用。我总是在应该在setState之后运行的函数中执行console.log。

2 个答案:

答案 0 :(得分:2)

您应该能够通过对购物车进行克隆/复制来解决此问题,而不是对正在缓存的同一购物车实例进行突变。一种解决方法可能是:

delete(index){

    // Use filter to clone the Cart array instance, while excluding 
    // the cart item that you want to delete (ie at index)
    const newCart = this.state.Cart.filter(function(item, i) { return i !== index });

    this.setState({deletedIndex:index, cachedCart:this.state.Cart, Cart: newCart },
        function(){
            console.log(this.state.cachedCart);
            Toast.show({
            text: 'Item deleted from Cart',
            position: 'bottom',
            buttonText: 'Undo',
            duration: 2000,
            onClose: this.undoDelete.bind(this)
        });
    });

}

答案 1 :(得分:1)

您的代码存在的问题是this.state.Cart.splice(index,1)返回已删除的项目,并且您已将该值设置为状态。

  delete(index){
    console.log("state", this.state);
    // Cloning the this.state.cart to updatedCart
    let updatedCart = this.state.cart.slice();
    // Removing the index element
    updatedCart.splice(index,1);
    
    this.setState({deletedIndex:index, cachedCart:this.state.cart, cart: updatedCart },
        ()=>{
          console.log("state", this.state);
    });

}

相关问题