即使该组件的props或state没有改变,也会调用React shouldComponentUpdate()

时间:2016-04-07 20:09:19

标签: reactjs

我将生命周期方法添加到我的React组件

  shouldComponentUpdate(nextProps, nextState) {
    console.log(nextProps, nextState);
    console.log(this.props, this.state);

    return false;  
  },

我的问题是,即使nextProps和nextState与当前的props和state完全相同,也会在组件上调用此方法。当我比较nextProps和this.props的console.log语句时,它们是完全相同的。与国家相同。

那么为什么要调用shouldComponentUpdate?

只要我改变父组件的状态就会调用它。但是实际组件中没有任何道具或状态发生变化。那么为什么叫呢?

fyi,我正在使用React with Meteor

进一步澄清:

我想知道为什么首先调用函数shouldComponentUpdate。该组件的状态或道具都没有变化。但是父组件的状态正在发生变化。

5 个答案:

答案 0 :(得分:17)

shouldComponentUpdate的目的是表明是否应该调用render。在您的情况下,某些父组件已呈现并指示它还要呈现子组件的实例。

shouldComponentUpdate是您缩短渲染时间的机会,并说“不要打扰,此处没有任何变化”。

现在,对于你的问题,"为什么它甚至被调用,因为没有改变"? React不会比较旧的和新的道具本身。你可以为你做一个mixin(即PureRenderMixin),但默认情况下React只是让渲染运行。

React没有进行比较的原因有两个原因。首先,与分析道具和状态相比,跳过渲染的性能节省可以忽略不计。由于React的渲染机制已经过优化以避免不必要的DOM操作,因此它可以假设组件需要更新并期望合理的性能。其次,进行比较并不是直截了当的。你的道具是一个原始的?,一个不可变的?,一个数组?一个复杂的对象?,是否需要深入比较?

React的模型是"默认情况下,我们会渲染所有要求的内容。如果您想要选择退出表现,请继续通过实施shouldComponentUpdate"来告诉我们。

答案 1 :(得分:14)

React会自动调用shouldComponentUpdate,它会在重新渲染过程开始之前触发(在这种情况下是你的父组件。)所以很自然地会经常调用它。

此函数的默认实现返回true,因此要停止重新渲染,您需要在此处返回false:

  shouldComponentUpdate(nextProps, nextState) {
    console.log(nextProps, nextState);
    console.log(this.props, this.state);

    return false;  
  }

Advanced Concerns, React page

  

因此,总而言之,React通过允许用户使用shouldComponentUpdate短路过程来避免执行协调DOM子树所需的昂贵DOM操作,

答案 2 :(得分:6)

每次都会调用

shouldComponentUpdate()

  • 每次重新渲染父组件都会更新道具。这包括使用完全相同的道具值进行重新渲染的所有场景。
  • 通过调用setState()来更新状态(反应允许的唯一方式)。这包括状态值完全相同的所有场景。

有时让重新渲染周期通过会很有用,即使新值与旧值完全相同。例如。当你的组件通过道具收到一个用户ID(可以保持不变),并从某个地方获取新消息并将它们置于状态时。

另外,'shouldComponentUpdate()`,作为检查更改的单独方法,只有在更改时才更新,可以生成可维护的代码:

  • 制作没有shouldComponentUpdate()的第一个版本,并确保同一组道具和状态导致呈现相同的结果。
  • 添加并调试shouldComponentUpdate()

调试接收输入(状态和道具)并呈现输出的“状态机”相对容易。 调试管理状态变化的机器要困难得多。

答案 3 :(得分:0)

shouldComponentUpdate() – Returns true or false value based on certain conditions. 
If you want your component to update, return true else return false. 
By default, it returns 

是。

if(shouldComponentUpdate) {
     // then render() is called and update UI/view 
}else{
   // then render() is not called ....[Don't update UI]
}

答案 4 :(得分:0)

shouldComponentUpdate 方法返回布尔值 指定React是否应继续进行渲染。

默认值为true。

何时使用shouldComponentUpdate: 当您希望当上一个状态值等于下一个状态值时不显示组件