防止不必要地重新渲染子元素

时间:2019-04-11 14:57:44

标签: reactjs dom rendering react-hooks

我正在React中创建一个全局通知组件,该组件使用createNotification向其子级提供Context句柄。通知与props.children一起呈现。如果没有更改,props.children是否可以阻止重新渲染?

我尝试不使用React.memouseMemo(props.children, [props.children])

const App = () => {
  return (
    <Notifications>
      <OtherComponent/>
    </Notifications/>
  );
}

const Notifications = (props) => {
  const [notifications, setNotifications] = useState([]);
  const createNotification = (newNotification) => {
    setNotifications([...notifications, ...newNotification]);
  }

  const NotificationElems = notifications.map((notification) => <Notification {...notification}/>);
  return (
    <NotificationContext.Provider value={createNotification}>
      <React.Fragment>
        {NotificationElems}
        {props.children}
      </React.Fragment>
    </NotificationContext.Provider>
  );
};

const OtherComponent = () => {
  console.log('Re-rendered');
  return <button onClick={() => useContext(NotificationContext)(notification)}>foo</button>
}

每次创建新的notification时,props.children都会重新渲染,即使其中实际上没有任何变化。它只是在旁边添加元素。如果您有一个大型应用程序,并且每个出现的notification都重新渲染,那么这可能会非常昂贵。如果没有办法防止这种情况,如何将其拆分,以便可以做到这一点:

<div>
  <OtherComponent/>
  <Notifications/>
</div>

并与OtherComponent的{​​{1}}句柄共享?

1 个答案:

答案 0 :(得分:3)

您需要使用useCallback钩子来创建createNotification命令式处理程序。否则,您将在Notifications组件的每次渲染上创建一个新函数,这将导致所有组件都要使用您的上下文进行重新渲染,因为每次添加通知时,您始终会传递新的处理程序。

您可能也不打算将newNotification散布到一系列通知中。

下一步,您需要在setNotifications中提供setState的updater callback version。它会传递当前的通知列表,您可以使用该列表追加新的通知。这使您的回调独立于通知状态的当前值。在不使用更新程序功能的情况下,根据当前状态更新状态通常是错误的,因为反应会批量处理多个更新。

const Notifications = props => {
    const [notifications, setNotifications] = useState([]);

    // use the useCallback hook to create a memorized handler
    const createNotification = useCallback(
        newNotification =>
            setNotifications(
                // use the callback version of setState
                notifications => [...notifications, newNotification],
            ),
        [],
    );

    const NotificationElems = notifications.map((notification, index) => <Notification key={index} {...notification} />);

    return (
        <NotificationContext.Provider value={createNotification}>
            <React.Fragment>
                {NotificationElems}
                {props.children}
            </React.Fragment>
        </NotificationContext.Provider>
    );
};

另一个问题是您有条件地调用了useContext钩子,这是不允许的。 Hooks must be called unconditionally

const OtherComponent = () => {
    // unconditiopnally subscribe to context
    const createNotification = useContext(NotificationContext);

    console.log('Re-rendered');

    return <button onClick={() => createNotification({text: 'foo'})}>foo</button>;
};

完整的示例:

Edit 31wx7q9y75

相关问题