reactjs - React hooks 被乱序调用

标签 reactjs typescript react-hooks

出于某种原因,useMemo 钩子(Hook)似乎在 useEffect 钩子(Hook)之前执行,位于其正上方。 我相信是这样,因为我收到一个错误:

TypeError: Cannot read property 'timestamp' of undefined

此错误指向最后一个 useEffect Hook 的依赖项数组中的 datum.timestamp,并且每当 is_pausedfalse => 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> 放置在组件的前面。

https://reactjs.org/docs/hooks-reference.html

关于reactjs - React hooks 被乱序调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59869264/

相关文章:

javascript - "export default from"不适用于 Babel React

reactjs - 隐藏多选选项-react-select

TypeScript:将字符串数组转换为其元素

TypeScript 动态对象迁移

reactjs - React useEffect 钩子(Hook)有条件地加载 onsnapshot

javascript - 如何使用 useState Hook 在 forEach 循环中设置状态

reactjs - Material UI select throws event.target.getAttribute 在react-datatable-component 中使用时不是一个函数

javascript - React 功能组件中的 Prop 名称

typescript - 在 Typescript 中使用函数参数进行隐式类型推断

javascript - 与异步自定义 react Hook 作斗争。如何等待一个钩子(Hook)的结果以在另一个钩子(Hook)中使用?