React: Parent component re-renders all children, even those that haven't changed on state change

后端 未结 4 1967
野性不改
野性不改 2020-11-30 03:33

I haven\'t been able to find a clear answer to this, hope this isn\'t repetitive.

I am using React + Redux for a simple chat app. The app is comprised of an InputBar

4条回答
  •  误落风尘
    2020-11-30 04:02

    If a parent component is updated, does React always update all the direct children within that component?

    No. React will only re-render a component if shouldComponentUpdate() returns true. By default, that method always returns true to avoid any subtle bugs for newcomers (and as William B pointed out, the DOM won't actually update unless something changed, lowering the impact).

    To prevent your sub-component from re-rendering unnecessarily, you need to implement the shouldComponentUpdate method in such a way that it only returns true when the data has actually changed. If this.props.messages is always the same array, it could be as simple as this:

    shouldComponentUpdate(nextProps) {
        return (this.props.messages !== nextProps.messages);
    }
    

    You may also want to do some sort of deep comparison or comparison of the message IDs or something, it depends on your requirements.

提交回复
热议问题