如何更新 Recoil.js 外部组件中的原子(状态)? (反应)

How to update atoms (state) in Recoil.js outside components ? (React)

我是 Recoil.js 的新手,我在应用程序中为登录用户提供了以下原子和选择器:

const signedInUserAtom = atom<SignedInUser | null>({
    key: 'signedInUserAtom',
    default: null
})

export const signedInUserSelector = selector<SignedInUser | null>({
    key: 'signedInUserSelector',
    get: ({ get }) => get(signedInUserAtom),
    set: ({ set, get }, newUserValue) => {
        // ... Do a bunch of stuff when a user signs in ...

        set(signedInUserAtom, newUserValue)
    }
})

所以基本上我使用 signedInUserSelector 来设置新用户。
现在,我想要一些函数来通过选择器设置用户,并在我的组件中使用它们,例如:

  export async function signInWithGoogleAccount() {
     const googleUser = async googleClient.signIn()
     // here I need to set the user atom like:
     //  const [user, setUser] = useRecoilState(signedInUserSelector)
     // setUser(googleUser)
  }

  export async function signInWithLocalAccount(email: string, password: string) {
     const localUser = async localClient.signIn(email, password)
     // here I need to set the user atom like:
     //  const [user, setUser] = useRecoilState(signedInUserSelector)
     // setUser(localUser)
  }

  export async function signOut() {
      await localClient.signOut()
      // here I need to set the user atom like:
     //  const [user, setUser] = useRecoilState(signedInUserSelector)
     // setUser(null)
  }

问题是因为这些函数没有在组件内部定义,所以我不能使用反冲钩子(比如 useRecoilState 访问 selectors/atoms)。

最后我想有什么组件可以做到:

function SignInFormComponent() {
  return <button onClick={signInWithGoogleAccount}>Sign In</button>
}

但是,如果 selectors/atoms 不在组件中,我如何访问 signInWithGoogleAccount 中的 selectors/atoms?

我认为唯一的方法(至少在几个月前)是一种 hack,其中包含一个使用反冲钩子并从中导出所提供函数的非渲染组件。

参见:https://github.com/facebookexperimental/Recoil/issues/289#issuecomment-777249693

下面是我自己的项目中实现此目的的文件,主要基于上面的 link。您需要做的就是将 <RecoilExternalStatePortal /> 放在应用程序树中保证 始终 呈现的任何位置。

这似乎是 Recoil API 中的遗漏,恕我直言。

import React from 'react'
import { Loadable, RecoilState, RecoilValue, useRecoilCallback, useRecoilTransactionObserver_UNSTABLE } from 'recoil'

/**
 * Returns a Recoil state value, from anywhere in the app.
 *
 * Can be used outside of the React tree (outside a React component), such as in utility scripts, etc.

 * <RecoilExternalStatePortal> must have been previously loaded in the React tree, or it won't work.
 * Initialized as a dummy function "() => null", it's reference is updated to a proper Recoil state mutator when RecoilExternalStatePortal is loaded.
 *
 * @example const lastCreatedUser = getRecoilExternal(lastCreatedUserState);
 */
export function getRecoilState<T>(recoilValue: RecoilValue<T>): T {
  return getRecoilLoadable(recoilValue).getValue()
}

/** The `getLoadable` function from recoil. This shouldn't be used directly. */
let getRecoilLoadable: <T>(recoilValue: RecoilValue<T>) => Loadable<T> = () => null as any

/**
 * Sets a Recoil state value, from anywhere in the app.
 *
 * Can be used outside of the React tree (outside a React component), such as in utility scripts, etc.
 *
 * <RecoilExternalStatePortal> must have been previously loaded in the React tree, or it won't work.
 * Initialized as a dummy function "() => null", it's reference is updated to a proper Recoil state mutator when RecoilExternalStatePortal is loaded.
 *
 * @example setRecoilExternalState(lastCreatedUserState, newUser)
 */
export let setRecoilState: <T>(recoilState: RecoilState<T>, valOrUpdater: ((currVal: T) => T) | T) => void = () =>
  null as any

/**
 * Utility component allowing to use the Recoil state outside of a React component.
 *
 * It must be loaded in the _app file, inside the <RecoilRoot> component.
 * Once it's been loaded in the React tree, it allows using setRecoilExternalState and getRecoilExternalLoadable from anywhere in the app.
 *
 * @see https://github.com/facebookexperimental/Recoil/issues/289#issuecomment-777300212
 * @see https://github.com/facebookexperimental/Recoil/issues/289#issuecomment-777305884
 * @see https://recoiljs.org/docs/api-reference/core/Loadable/
 */
export function RecoilExternalStatePortal() {
  // We need to update the getRecoilExternalLoadable every time there's a new snapshot
  // Otherwise we will load old values from when the component was mounted
  useRecoilTransactionObserver_UNSTABLE(({ snapshot }) => {
    getRecoilLoadable = snapshot.getLoadable
  })

  // We only need to assign setRecoilExternalState once because it's not temporally dependent like "get" is
  useRecoilCallback(({ set }) => {
    setRecoilState = set

    return async () => {
      // no-op
    }
  })()

  return <></>
}

正如我在 another answer, you generally don't want to run into this, but if you eventually really need to update atoms outside of React Components you might give a try to Recoil Nexus 中指出的那样。

在您拥有 RecoilRoot 的同一个文件中,您将拥有如下内容:

import React from 'react';
import { RecoilRoot } from "recoil"
import RecoilNexus from 'recoil-nexus'

export default function App() {
  return (
    <RecoilRoot>
      <RecoilNexus/>
      
      {/* ... */}
      
    </RecoilRoot>
  );
};


export default App;

然后,在任何需要 read/update 值的地方:

import yourAtom from './yourAtom'
import { getRecoil, setRecoil } from 'recoil-nexus'

最终您可以像这样获取和设置值:


const loading = getRecoil(loadingState)

setRecoil(loadingState, !loading)

就是这样!

免责声明:我是图书馆的作者。


检查此 CodeSandbox 以获取实际示例。

我认为在 React 中处理这个问题的正确方法是使用自定义 hook/facade。这样你可以保持代码集中,但与需要它的组件共享,在这种情况下,在组件中包含依赖于 hooks/being 的代码。这篇文章解释得很好:

https://wanago.io/2019/12/09/javascript-design-patterns-facade-react-hooks/

但基本思想是您将创建一个自定义 useAuth 挂钩,它将公开您需要的内容:

export function useAuth() {
  const [auth, setAuth] = useRecoilState(authAtom);
  const resetAuth = useResetRecoilState(authAtom);
  const authState = useMemo(() => {
    return {
      isAuthenticated: () => {
        return !!auth.accessToken && auth.expiresAt > new Date();
      },
    };
  }, [auth]);
  ...
  return { auth, authState, logout: resetAuth, /* and maybe more, error, login, etc */ };

然后在需要auth的组件中使用:

const AuthorizedComponent: FC<Props> = (props) => {
  const { auth, authState } = useAuth();