我成功地改编了https://github.com/facebookexperimental/Recoil/issues/289#issuecomment-777249693中的答案,并使其与Next.js框架配合使用。(请参见下面的用法示例)
这个解决方案允许使用Recoil Root作为一种全局状态。但是,仅当只有一个 RecoilRoot
组件时才能正常工作。
import {
Loadable,
RecoilState,
RecoilValue,
useRecoilCallback,
useRecoilTransactionObserver_UNSTABLE,
} from 'recoil';
export let getRecoilExternalLoadable: <T>(
recoilValue: RecoilValue<T>,
) => Loadable<T> = () => null as any;
export let setRecoilExternalState: <T>(
recoilState: RecoilState<T>,
valOrUpdater: ((currVal: T) => T) | T,
) => void = () => null as any;
export function RecoilExternalStatePortal() {
useRecoilTransactionObserver_UNSTABLE(({ snapshot }) => {
getRecoilExternalLoadable = snapshot.getLoadable;
});
useRecoilCallback(({ set }) => {
setRecoilExternalState = set;
return async () => {
};
})();
return <></>;
}
使用Next.js框架的配置示例:
import {
NextComponentType,
NextPageContext,
} from 'next';
import { Router } from 'next/router';
import React from 'react';
import { RecoilRoot } from 'recoil';
import { RecoilExternalStatePortal } from '../components/RecoilExternalStatePortal';
type Props = {
Component: NextComponentType<NextPageContext>;
err?: Error;
pageProps: any;
router?: Router;
};
const App: React.FunctionComponent<Props> = (props): JSX.Element => {
const { Component, pageProps} = props;
return (
<RecoilRoot>
<Component {...pageProps} />
<RecoilExternalStatePortal />
</RecoilRoot>
);
};
const createUser = (newUser) => {
setRecoilExternalState(lastCreatedUserState, newUser)
}
RecoilRoot
组件。 但是,也许您可以提供一些伪代码,以便我更好地理解问题和您想要做什么。 - Johannes KlaußRecoilRoot
,人们可能会认为它是全局存储。 - Vadorequest