我在我的反应项目中使用后坐力(recoiljs.org)。
我有一个相当经典的项目列表设置--对象图如下所示:
Routes - routes is an array of Route objects
- Route - route object is edited in a form我使用一个原子来表示当前选择的路由数组。
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函数允许某人更新单个路由状态,并将其复制到任何呈现路由中。
但是,我想自动保存对整个图的任何更改,但不知道如何轻松地观察到对路由父对象的任何更改。是否有一种以编程方式订阅更新以便序列化和保存此状态的方法?
发布于 2021-07-29 10:00:37
您只需使用useEffect即可:
const currentState = useRecoilValue(currentRoutesViewState);
useEffect(() => {
// currentState changed.
// save the current state
}, [currentState])https://stackoverflow.com/questions/68565926
复制相似问题