首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >以编程方式观察反冲的变化

以编程方式观察反冲的变化
EN

Stack Overflow用户
提问于 2021-07-28 18:50:28
回答 1查看 725关注 0票数 1

我在我的反应项目中使用后坐力(recoiljs.org)。

我有一个相当经典的项目列表设置--对象图如下所示:

代码语言:javascript
复制
Routes - routes is an array of Route objects
- Route - route object is edited in a form

我使用一个原子来表示当前选择的路由数组。

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

我还使用一个selectorFamily来允许单个控件绑定和更新单个项的状态。

代码语言:javascript
复制
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函数允许某人更新单个路由状态,并将其复制到任何呈现路由中。

但是,我想自动保存对整个图的任何更改,但不知道如何轻松地观察到对路由父对象的任何更改。是否有一种以编程方式订阅更新以便序列化和保存此状态的方法?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-29 10:00:37

您只需使用useEffect即可:

代码语言:javascript
复制
const currentState = useRecoilValue(currentRoutesViewState);

useEffect(() => {
  // currentState changed.
  // save the current state
}, [currentState])
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68565926

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档