React备忘录无法捕获prevPropsnextProps的道具,并且组件无法很好地渲染。反应文档说


如果您的功能组件使用相同的道具呈现相同的结果,则可以将其包装在对React.memo的调用中以提高性能。


我的问题是使用react memo停止两次渲染,但是备忘录似乎不起作用,并且组件使用相同的props渲染两次。

Create New Event上单击/events时,组件将呈现

here is the live sandbox


子组件位于/components/Event/CreateEvent/CreateEvent.js
父组件位于触发子组件的/Pages/Event/Event.js行号999'


这是代码:

import React from "react";
import AuthContext from "../../context/global-context";
import CreateEvent from "../../components/Event/CreateEvent/CreateEvent";

function Events({ location }) {

  // Sate Managing
  const [allEvents, setAllEvents] = React.useState([]);
  const [creating, setCreating] = React.useState(false);

  // Context As State
  const { token, email } = React.useContext(AuthContext);

  // Creating Event Showing
  const modelBoxHandler = () => {
    // works on when the ViewEvent is open
    if (eventSelected) {
      setEventSelected(null);
      return;
    }

    setCreating(!creating);
  };

  return (
    <div className="events">

      {/* New Event Creating */}
      {creating && (
        <CreateEvent onHidder={modelBoxHandler} allEvents={allEvents} />
      )}

      {console.log("Event Rendered.js =>")}

    </div>
  );
}

export default React.memo(Events, () => true);


Rect备忘录没有道具的子组件:

import React from "react";
import AuthContext from "../../../context/global-context";

function CreateEvent({ onHidder, allEvents }) {
  // Context
  const { token } = React.useContext(AuthContext);

  console.log("CreatedEvent.js REnder");
  return (
       ... Some code here
  );
}

export default React.memo(CreateEvent, (prevProps, nextProps) => {
  console.log("Hello", prevProps, nextProps);
});


预先感谢您的宝贵答复和宝贵时间!

最佳答案

问题是基于creating变量,您实际上是在重新安装而不渲染CreateEvent组件。它的意思是,如果创建变量时发生更改,则在创建时将卸载该组件并重新安装它为true,因此它不会重新渲染

还必须注意,modelBoxHandler函数引用在每次重新渲染时也会更改,因此即使您的CreateEvent组件处于渲染状态并且父级由于某种原因而被重新渲染,CreateEvent组件也将重新渲染

您需要进行2项更改才能使其更好地工作


使用useCallback钩子定义modelBoxHandler
根据创建道具在createEvent中执行条件渲染



 // Creating Event Showing
  const modelBoxHandler = useCallback(() => {
    // works on when the ViewEvent is open
    if (eventSelected) {
      setEventSelected(null);
      return;
    }

    setCreating(prevCreating => !prevCreating);
  }, [eventSelected]);
   ...
    return (
        <div className="events">

          {/* New Event Creating */}
          <CreateEvent creating={creating} onHidder={modelBoxHandler} allEvents={allEvents} />

          {console.log("Event Rendered.js =>")}

        </div>
    );



并在createEvent中

function CreateEvent({ onHidder, allEvents, creating }) {
  // Context
  const { token } = React.useContext(AuthContext);

  console.log("CreatedEvent.js REnder");
  if(!creating) {
     return null;
  }
  return (
       ... Some code here
  );
}

export default React.memo(CreateEvent);

08-15 18:28