简体   繁体   English

React.memo 行为

[英]React.memo behaviour

Consider the following simple components:考虑以下简单组件:

import React, { Fragment, memo } from 'react';

function Parent(props) {
  return (
    <Fragment>
      <Child {...props} />
      <Child foobar={props.foobar} />
    </Fragment>
  );
}

export default memo(Parent);
import React, { memo } from 'react';

function Child({ foobar }) {
  return (
    <p>{foobar}</p>
  );
}

export default memo(Child);

From what I understand wrapping a component in React.memo() will ensure that it only gets re-rendered whenever its props changes.据我所知,在 React.memo() 中包装一个组件将确保它只在它的 props 改变时重新渲染。

So unless whatever props that is passed onto "Parent" changes, that component, and its entire lineage of children will not get re-rendered.因此,除非传递给“Parent”的任何道具发生变化,否则该组件及其整个子代将不会重新渲染。

However, what about its two children?然而,它的两个孩子呢? Understandably if "props.fooobar" changes, they both will get re-rendered.可以理解的是,如果“props.fooobar”发生变化,它们都会被重新渲染。 But what if "props.somethingElse" gets changed?但是如果“props.somethingElse”被改变了呢? Which of them will get re-rendered here?其中哪些会在此处重新渲染?

If another prop than fooobar given to the Parent component changes, the Parent component will be re-rendered, but the first Child component will also be re-rendered since that is given all of the props given to the parent, so its props will also change.如果给Parent组件的除了fooobar之外的另一个 prop 发生变化, Parent组件将被重新渲染,但第一个Child组件也将被重新渲染,因为它被赋予了所有给父组件的 props,所以它的 props 也将被重新渲染改变。

Example例子

 const { memo, Fragment } = React; const Parent = memo(props => { console.log("Rendered Parent"); return ( <Fragment> <Child {...props} /> <Child foobar={props.foobar} /> </Fragment> ); }); const Child = memo(({ foobar }) => { console.log("Rendered Child"); return <p>{foobar}</p>; }); class App extends React.Component { state = { foobar: "foo", bazqux: "baz" }; componentDidMount() { setTimeout(() => this.setState({ foobar: "bar" }), 1000) setTimeout(() => this.setState({ bazqux: "qux" }), 2000) } render() { const { foobar, bazqux } = this.state; return <Parent foobar={foobar} bazqux={bazqux} />; } } ReactDOM.render(<App />, document.getElementById("root"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

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

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