简体   繁体   English

React 使用 setState 更新对象但不重新渲染

[英]React use setState to update object but not re-render

I want to use setState to update the object in state which called 'all_cart",我想使用 setState 来更新状态为“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.但无论我尝试哪种方法,它都无法触发重新渲染,我知道 React 将使用===来检查状态中的两个对象是否更改。

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?我能怎么做?

According to the React docs if you have props, it is wrong approach:根据React 文档,如果你有道具,这是错误的方法:

// 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.要修复它,请使用第二种形式的 setState(),它接受一个函数而不是一个对象。 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.因此,可以在这里看到一个完整的 stackblitz 示例

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根据我的理解,您想将_response['data'].data.cart_data与现有状态all_cart 合并,在这种情况下,您应该试试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM