Home > Software design >  React use setState to update object but not re-render
React use setState to update object but not re-render

Time:07-22

I want to use setState to update the object in state which called 'all_cart",

but not matter which method I tryed, it cannot trigger re-render, I know React will use === to check two object in state is changed or not.

Here is my code:

this.setState({
    all_cart: {
        ...this.state.all_cart,
        cart_data : _response['data'].data.cart_data
    }
})

this.setState(({all_cart}) => ({
    all_cart: {
        ...this.state.all_cart,
        cart_data : _response['data'].data.cart_data
    }
}))

How can I do?

CodePudding user response:

According to the React docs if you have props, it is wrong approach:

// Wrong
this.setState({
  counter: this.state.counter   this.props.increment,
});

To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:

// Correct
this.setState((state, props) => ({
  counter: state.counter   props.increment
}));

And your code would look like this:

this.setState((state, props) => ({
    all_cart: {
        ...state.all_cart,
        cart_data : _response['data'].data.cart_data
    }
}))

UPDATE:

However, if you do not use props, then it looks like your function is not is scope, so try to use arrow function. Let me show an example:

handleClick = () => {
    this.setState(this.someApiResult())
}

So a complete stackblitz example can be seen here.

CodePudding user response:

As per my understanding, you want to merge _response['data'].data.cart_data with the existing state which is all_cart, in this case, you should try this

function updateCart(){
const updatedData = {...this.state.all_cart, ..._response['data'].data.cart_data};
this.setState({all_cart: updatedData});
}
  • Related