ReactJS,使用相同的参数调用 setState [英] ReactJS, Calling setState with same parameter
问题描述
我一直在阅读 React 文档并遇到了 shouldComponentUpdate()
.我的理解是每次调用 setState()
时,都会更新该组件的重新渲染.
I have been reading the React docs and came across shouldComponentUpdate()
. My understanding is that everytime setState()
is called, a re-render of that component will be updated.
我的问题是,如果要更新的值与当前状态值 SAME 相同,是否会触发重新渲染事件?或者我必须在 shouldComponentUpdate()
My question is that If the value to be updated is the SAME as the current state value, would this trigger a re-render event? or I would have to manually checks for the current value and value to be updated in shouldComponentUpdate()
推荐答案
React 官方文档说明:
The official React documentation states:
默认行为是在每次状态更改时重新渲染...
The default behavior is to re-render on every state change...
https://reactjs.org/docs/react-component.html#shouldcomponentupdate
这意味着默认情况下,如果任何组件的 state
或 props
值发生变化,render()
将被执行.
This means that by default, render()
will be executed if any of a component's state
or props
values changes.
您可以使用 shouldComponentUpdate() 覆盖此默认行为.这是一个仅在状态值更改时更新的示例.
You can override this default behavior using shouldComponentUpdate(). Here's an example that only updates if a state value changes.
shouldComponentUpdate(nextProps, nextState) {
return this.state.someValue !== nextState.someValue;
}
注意:这个例子完全忽略了props
.因此,对 props
的任何更改都不会触发 render()
.
Note: this example completely ignores props
. So, any changes to props
will not trigger render()
.
这篇关于ReactJS,使用相同的参数调用 setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!