简体   繁体   English

如何在启动时只渲染一次 React 组件?

[英]How to render React components only once on startup?

I've been reading docs about performance but I can't find the answer to my question...我一直在阅读有关性能的文档,但找不到我的问题的答案...

I have a bunch of buttons on my application that will render based on some properties but not state, parent components will never change their properties.我的应用程序上有一堆按钮,它们将基于某些属性而不是状态呈现,父组件永远不会改变它们的属性。 Then I have this onKeyDown event handler that will listen for some keys and update another component.然后我有这个onKeyDown事件处理程序,它将侦听一些键并更新另一个组件。

My problem is that when pressing keys and updating this one component, all the other buttons will render too (observed through React dev tools for Chrome).我的问题是,当按下键并更新这个组件时,所有其他按钮也会呈现(通过 Chrome 的 React 开发工具观察)。 I haven't implemented shouldComponentUpdate(nextProps, nextState) on my buttons, but shouldn't React have this behavior by default?我还没有在我的按钮上实现shouldComponentUpdate(nextProps, nextState) ,但是 React 默认不应该有这种行为吗? I mean, compare this.props with nextProps and if they are exactly the same, do not call render() ?我的意思是,将this.propsnextProps进行比较,如果它们完全相同,请不要调用render()

Am I supposed to do this myself for every component that should only render once on application startup?我是否应该为每个只应在应用程序启动时呈现一次的组件自己执行此操作?

EDIT: PureComponent seems solve the problem... But instead of creating a new question, I'm updating this one with a related question:编辑: PureComponent似乎解决了问题......但我没有创建一个新问题,而是用一个相关问题更新了这个问题:

Why wouldn't the documentation recommend to have all components based on PureComponent by default?为什么文档不建议默认使用基于 PureComponent 的所有组件? What are the arguments against using PureComponent by default instead of the typical Component ?默认情况下,反对使用PureComponent而不是典型的Component的论据是什么?

Pure components should solve your problem because they implement shallow prop and state comparison by default.纯组件应该可以解决您的问题,因为它们默认实现了浅层的 prop 和 state 比较。

Link to the docs. 链接到文档。

If your React component's render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.如果你的 React 组件的 render() 函数在给定相同的 props 和 state 的情况下呈现相同的结果,你可以在某些情况下使用 React.PureComponent 来提升性能。

One way to make sure a React component is rendered only once, is by making shouldComponentUpdate return false :确保 React 组件只呈现一次的一种方法是让shouldComponentUpdate返回false

class MyComponent extends React.Component {

  shouldComponentUpdate = () => false

  render() {
    return <div>{ this.props.children }</div>;
  }
}

In the example above, even if this.props.children changes, the component won't render again.在上面的例子中,即使this.props.children改变了,组件也不会再次渲染。 It will render only once, when mounted.安装后,它只会渲染一次。

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

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