链接用户身份 — React Native SDK
Atlas Device SDK 已弃用。 有关详细信息,请参阅弃用页面。
Realm提供许多身份验证提供程序,用于将用户日志到您的应用。 每个提供商都会创建一个唯一的用户身份。 Realm允许您将多个档案合并为一个用户凭证。
您可以将身份与useUser 钩子关联。
1
2
设置提供商
您需要先登录用户,然后才能关联身份。 这意味着您需要 AppProvider
和UserProvider
。 然后,您可以在UserProvider
内的任何组件中将身份链接到当前用户。
export const LinkIdentities = () => { return ( <AppProvider id={APP_ID}> <UserProvider fallback={LogIn}> <RegisterUser /> </UserProvider> </AppProvider> ); }; // Log in an anonymous user. This component only mounts // if there is no authenticated user. const LogIn = () => { const {logInWithAnonymous} = useAuth(); return ( <View> <Text>No one is logged in yet.</Text> <Pressable onPress={logInWithAnonymous}> <Text style={styles.buttonText}>Log in</Text> </Pressable> </View> ); };
3
创建用户界面和链接标识
以下示例呈现与应用的当前用户关联的每个身份的用户 ID。 最初,仅显示匿名用户身份,但您可以创建电子邮件/密码身份并将其链接到匿名用户。
type UserIdentity = { providerType: string; id: string; }; // Link an anonymous user to an email/password identity. // For this example, the App Services backend automatically // confirms users' emails. const RegisterUser = () => { const app = useApp(); const user = useUser(); const {logOut} = useAuth(); const {register, result} = useEmailPasswordAuth(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [userIdentities, setUserIdentities] = useState(user.identities); // Use `result` to react to successful registration // by linking credentials with the current user. useEffect(() => { if (result.operation === AuthOperationName.Register && result.success) { linkCredentials(); } }, [result]); if (!userIdentities.length) { setUserIdentities(user.identities); } const linkCredentials = async () => { const credentials = Credentials.emailPassword(email, password); await user.linkCredentials(credentials); setUserIdentities(user.identities); }; const registerAndLinkIdentities = async () => { register({email, password}); }; const deleteUser = async () => { app.deleteUser(app.currentUser!); }; return ( <View> {/* Show all identities associated with the current user */} <FlatList data={userIdentities} renderItem={({item}) => ( <Text >ID: {item.id}</Text> )} keyExtractor={item => item.id} /> <Text>Link anonymous user with email/password account</Text> <View> <TextInput onChangeText={setEmail} value={email} placeholder="email..." /> <TextInput onChangeText={setPassword} value={password} placeholder="password..." /> </View> <View> <Pressable onPress={registerAndLinkIdentities}> <Text style={styles.buttonText}>Register</Text> </Pressable> <Pressable onPress={logOut}> <Text style={styles.buttonText}>Log out</Text> </Pressable> <Pressable onPress={deleteUser}> <Text style={styles.buttonText}>Delete user</Text> </Pressable> </View> </View> ); };