我是 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
访问选择器/原子)。
最后,我希望有任何组件能够做到:
function SignInFormComponent() {
return <button onClick={signInWithGoogleAccount}>Sign In</button>
}
signInWithGoogleAccount
但是,如果它不在组件中,我如何访问选择器/原子?