React 备忘录没有捕获道具,无论是prevProps
还是nextProps
,组件渲染良好。反应文档说
- 如果您的函数组件在给定相同的 props 的情况下呈现相同的结果,您可以将其包装在对 React.memo 的调用中以提高性能。
我的问题是使用 React 备忘录停止两次渲染,但备忘录似乎不起作用,并且组件使用相同的道具渲染两次。
单击Create New Event
时,组件将呈现/events
这是实时沙盒。
子组件位于
/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);
矩形备忘录没有道具的子组件:
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
- 在创建事件中执行条件渲染基于创建道具
// 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>
);
并在创建事件中
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);
在您的示例中,您没有额外的渲染可供React.memo
工作。
根据渲染逻辑,没有任何nextProps
,使用条件渲染(creating
(卸载组件。
// You toggle with `creating` value, there is only single render each time
creating && <CreateEvent onHidder={modelBoxHandler} allEvents={allEvents}/>
// Works, because there will be multiple renders (nextProps)
true && <CreateEvent onHidder={modelBoxHandler} allEvents={allEvents} />
在这种情况下,您可能不需要React.memo
。