【问题标题】:Programmatically observing changes in Recoil with React使用 React 以编程方式观察 Recoil 的变化
【发布时间】:2021-07-28 18:50:28
【问题描述】:

我在我的 react 项目中使用 Recoil (recoiljs.org)。

我有一个带有项目列表的相当经典的设置 - 对象图看起来像这样:

Routes - routes is an array of Route objects
- Route - route object is edited in a form

我用一个原子来表示当前选中的Routes数组,例如

const [routes, setRoutes] = useRecoilValue(currentRoutesViewState);

我还使用selectorFamily 来允许单个控件绑定到单个项目并更新其状态。

const routeSelectorFamily = selectorFamily({
  key: "routeSelectorFamily",
  get:
    (routeKey) =>
    ({ get }) => {
      const routes = get(currentRoutesViewState);
      return routes.find((r) => r.key === routeKey);
    },
  set:
    (routeKey) =>
    ({ set }, newValue) => {
      set(currentRoutesViewState, (oldRoutes) => {
        const index = oldRoutes.findIndex((r) => r.key === routeKey);
        const newRoutes = replaceItemAtIndex(
          oldRoutes,
          index,
          newValue as RouteViewModel
        );
        return newRoutes;
      });
    },
});

如您所见,set 函数允许某人更新单个路由状态,并将其复制到任何渲染路由中。

但是,我想自动保存对整个图表的任何更改,但不知道如何轻松观察对 Routes 父对象的任何更改。有没有办法以编程方式订阅更新,以便我可以序列化并保存此状态?

【问题讨论】:

    标签: reactjs recoiljs


    【解决方案1】:

    您可以为此使用useEffect

    const currentState = useRecoilValue(currentRoutesViewState);
    
    useEffect(() => {
      // currentState changed.
      // save the current state
    }, [currentState])
    
    

    【讨论】:

    • 有趣,这是个好主意。我假设无论值是否已更改,这将在挂载时至少触发一次 - 所以我需要以某种方式正确跟踪对该方法的调用 - 以确定状态是否已更改?
    • 没错,useEffect 将在组件挂载时运行一次。您可以添加一个状态作为称为 didUpdateisDirty 的标志,并在第一次运行时将其设置为 true 并检查标志以保存当前状态。
    猜你喜欢
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    相关资源
    最近更新 更多