出于某种原因,useMemo 钩子(Hook)似乎在 useEffect 钩子(Hook)之前执行,位于其正上方。 我相信是这样,因为我收到一个错误:
TypeError: Cannot read property 'timestamp' of undefined
此错误指向最后一个 useEffect Hook 的依赖项数组中的 datum.timestamp
,并且每当 is_paused
从 false => true
更改时就会发生>.
在我看来,问题是 useMemo 钩子(Hook)试图从空数组中获取一个项目,该数组应该在其之前由 useEffect 设置。
我做了一些日志记录,确实,我在 useMemo 中看到了日志,但没有在 useEffect 中看到日志。
const [position, setPosition] = useState(MAX_HISTORY - 1);
const [data, setData] = useState<ExData[]>(new Array(MAX_HISTORY).fill({ content: {} }));
const paused_data_ref = useRef<ExData[]>([]);
useEffect(() => {
const listener = (d: ExData) => {
const new_data = data.slice(1);
new_data.push(d);
setData(new_data);
};
addListener(props.event_key, listener);
return () => {
removeListener(props.event_key);
};
});
useEffect(() => {
paused_data_ref.current = is_paused ? [...data] : [];
if (is_paused) {
console.log('copy data array');
}
}, [is_paused, data]);
const datum = useMemo(() => {
if (is_paused)
console.log({
position,
data: paused_data_ref.current[position],
arr: paused_data_ref.current
});
return is_paused ? paused_data_ref.current[position] : data[MAX_HISTORY - 1];
}, [is_paused, position, data]);
useEffect(() => {...}, [datum.timestamp])
最佳答案
你是对的,传递给 useEffect
的函数是在传递给 useMemo
的函数之后调用的。
根据 React 文档:
The function passed to useEffect will run after the render is committed to the screen.
这意味着所有 useEffect
调用都将在组件中的其他函数(包括传递给 useMemo
的函数)之后发生,即使 useEffect
code> 放置在组件的前面。
关于reactjs - React hooks 被乱序调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59869264/