技术栈:umijs@4 zustand@^4.5.2 react-flow@^11.11.2
需求:
image.png
上图的text数据存在了zustand中,画布中所有的数据都存在了zustand,
之前点击右上角的保存是用如下代码实现的,

export const useSaveGraph = () => {
  const { data } = useFetchFlow();
  const { setFlow } = useSetFlow();
  const { id } = useParams();
  const { nodes, edges } = useGraphStore((state) => state);
  const saveGraph = useCallback(async () => {
    const dslComponents = buildDslComponentsByGraph(nodes, edges);
    return setFlow({
      id,
      title: data.title,
      dsl: { ...data.dsl, graph: { nodes, edges }, components: dslComponents },
    });
  }, [nodes, edges, setFlow, id, data]);

  return { saveGraph };
};

dslComponents为后端在意的信息,graph为画布中算子的坐标信息等。之前每次点击右上角的保存按钮都调用该函数,构建出后端关心的dslComponents数据。现在需要将图中的text保存nodes下,如下图的value
image.png
根据上述代码,我需要在调用接口前将text:"geek"拼接到上图的zustand数据结构中,如下图
b1a0cc8cc993e1a2146c2bc1b114c41.png

handleRunAgent

export const useSaveGraphBeforeOpeningDebugDrawer = (show: () => void) => {
  const { id } = useParams();
  const { saveGraph } = useSaveGraph();
  const { resetFlow } = useResetFlow();
  const { refetch } = useFetchFlow();
  const { send } = useSendMessageWithSse(api.runCanvas);
  const handleRun = useCallback(async () => {
    const saveRet = await saveGraph();
    if (saveRet?.code === 0) {
      // Call the reset api before opening the run drawer each time
      const resetRet = await resetFlow();
      // After resetting, all previous messages will be cleared.
      if (resetRet?.code === 0) {
        // fetch prologue
        const sendRet = await send({ id });
        if (receiveMessageError(sendRet)) {
          message.error(sendRet?.data?.message);
        } else {
          refetch();
          show();
        }
      }
    }
  }, [saveGraph, resetFlow, id, send, show, refetch]);

  return handleRun;
};

  const { handleRun } = useSaveGraphBeforeOpeningDebugDrawer(showChatModal!);

  const handleRunAgent = useCallback(() => {
    handleRun(); // 调用接口
    hideModal?.();
  }, [handleRun, hideModal]);

但是无论我怎么设置setTimeout间隔时间,都拿不到最新的表单数据,每当我遇到用setTimeout时候就觉得逻辑没理顺,实现起来太别扭了。矛盾的地方在于调用接口的时候拿不到zustand中最新的数据。经过老弟的提示,觉得得换个思路,于是乎:
80330b6cc3b7b3e72a8accbea06f871.png

4c679f681be1b850adce89b432ae7fd.png

b632c3f9727d4291b602ab32fe0886f.png

解决办法:
由上图可以看出将updateNodeForm修改后的nodes直接返回,然后传递给接口,而不是去等待页面上的zustand更新。很多时候思维会进入死胡同,这时候换个脑筋问题迎刃而解。


assassin_cike
1.3k 声望74 粉丝

生活不是得过且过


« 上一篇
tailwindcss 实践
下一篇 »
recharts 实践