React.js:使用shouldComponentUpdate()在特定状态更改时停止重新呈现

Dav*_*vid 2 reactjs

我的组件onload中有多个setState。单击下拉值时,我的页面正在重新呈现,因为单击时我通过来存储这些值setState

为了停止点击重新渲染,我在使用以下代码。

shouldComponentUpdate() {
    return false
}
Run Code Online (Sandbox Code Playgroud)

现在,由于具有上述功能,页面加载时我的值未存储在状态中。我还有什么需要做的吗?

Shu*_*tri 6

您指出您的组件中没有显示更改,因为您已经falseshouldComponentUpdate方法中返回了,因为它根本不会重新更改。

如果要限制特定状态更改的呈现,则只需检查该状态并返回false,否则返回true

shouldComponentUpdate(nextProps, nextState) {
     if(this.state.dropdownVal != nextState.dropdownval) {
          return false
     }
     return true
}
Run Code Online (Sandbox Code Playgroud)

但是,重新渲染并不是一件坏事,因为React渲染过程非常高效,并且您希望不经常显示DOM中的更新状态。


Dha*_*tel 0

你必须使用shouldComponentUpdate()类似的

  shouldComponentUpdate(nextProps, nextState) {
    return !Immutable.is(this.state.synergy, nextState.synergy)
 }
Run Code Online (Sandbox Code Playgroud)