[英]REACT Props is undefined in useLayoutEffect
在我的父组件中,我将 prop mainPostion
传递给 cursor 组件,但问题是useLayoutEffect
挂钩内的 prop 未定义,而useLayoutEffect
外的 prop 已定义。
import { useLayoutEffect, useRef } from "react";
import { StyledCursor } from "../../setup/styled_components/styled_component";
const Cursor = ({ darkModeButtonPosition, mainPostion }) => {
console.log("mainPostion: ", mainPostion); //defined
const cursorRef = useRef(null);
const onMouseMove = (event) => {
const { clientX, clientY } = event;
cursorRef.current.style.left = `${clientX - 15}px`;
cursorRef.current.style.top = `${clientY - 15}px`;
console.log("mainPostion: ", mainPostion); // defined
};
useLayoutEffect(() => {
// FIXME? why mainPostion here is undefind and outside is defined
console.log("mainPostion: ", mainPostion);
document.addEventListener("mousemove", onMouseMove);
return () => {
document.removeEventListener("mousemove", onMouseMove);
};
}, []);
return (
<StyledCursor
ref={cursorRef}
animate={{ scale: [1, 0.8, 1] }}
transition={{
duration: 2,
loop: Infinity,
type: "tween",
}}
></StyledCursor>
);
};
export default Cursor;
所以组件第一次呈现时(因为没有 DOM 突变)所有外部上下文变量都还没有定义。
如果您改用 useEffect,则不会遇到此问题。 对于我在您的代码中看到的内容,您不需要在 DOM 突变后立即运行该代码。
因此,将其更改为使用 useEffect 应该是直接的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.