React Navigation v5 Authentication Flows (Screens as Different Files)

女生的网名这么多〃 提交于 2020-06-29 03:48:55

问题


If we see in the doc example: https://reactnavigation.org/docs/auth-flow/ :

function SignInScreen() {
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');

  const { signIn } = React.useContext(AuthContext); // ????

  return (
    <View>
      <TextInput
        placeholder="Username"
        value={username}
        onChangeText={setUsername}
      />
      <TextInput
        placeholder="Password"
        value={password}
        onChangeText={setPassword}
        secureTextEntry
      />
      <Button title="Sign in" onPress={() => signIn({ username, password })} />
    </View>
  );
}

SignInScreen is located in the same App.js. If we put out SignInScreen as a new file SignInScreen.js, how to dispatch the signIn from SignInScreen.js?


回答1:


You must have a wrapper for SignInScreen

// App.js
import SignInScreen from '...'

// Export the context
export const AuthContext = React.createContext();

export default function App() {
  // ... some bootstrap code
  // https://reactnavigation.org/docs/auth-flow/#implement-the-logic-for-restoring-the-token
  const authContext = React.useMemo(
    () => ({
      signIn: async (data) => { ... },
    }),
    []
  );

  return (
    <AuthContext.Provider value={authContext}>
      <SignInScreen />
    </AuthContext.Provider>
  );
}
import { AuthContext } from "./App.js"

function SignInScreen() {
  // Must be child of AuthContext.Provider
  const { signIn } = React.useContext(AuthContext);

  return (
    <View>
      ...
    </View>
  );
}


来源:https://stackoverflow.com/questions/62360479/react-navigation-v5-authentication-flows-screens-as-different-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!