在React Native应用程序中,将userToken
从登录过程传递到应用程序的其他组件通常涉及以下几个步骤:
userToken
存储在设备上,以便跨会话使用。userToken
。以下是使用Context API和Redux两种方法的示例。
import React from 'react';
const AuthContext = React.createContext();
class AuthProvider extends React.Component {
state = {
userToken: null,
};
login = (token) => {
this.setState({ userToken: token });
};
logout = () => {
this.setState({ userToken: null });
};
render() {
return (
<AuthContext.Provider value={{ ...this.state, login: this.login, logout: this.logout }}>
{this.props.children}
</AuthContext.Provider>
);
}
}
import React from 'react';
import { AuthProvider } from './path/to/AuthContext';
import MainApp from './MainApp';
export default function App() {
return (
<AuthProvider>
<MainApp />
</AuthProvider>
);
}
import React, { useContext } from 'react';
import { AuthContext } from './path/to/AuthContext';
const SomeComponent = () => {
const { userToken } = useContext(AuthContext);
return (
<div>
{userToken ? `Logged in with token: ${userToken}` : 'Not logged in'}
</div>
);
};
npm install redux react-redux
import { createStore } from 'redux';
const initialState = {
userToken: null,
};
function authReducer(state = initialState, action) {
switch (action.type) {
case 'LOGIN':
return { ...state, userToken: action.payload };
case 'LOGOUT':
return { ...state, userToken: null };
default:
return state;
}
}
const store = createStore(authReducer);
import React from 'react';
import { Provider } from 'react-redux';
import store from './path/to/store';
import MainApp from './MainApp';
export default function App() {
return (
<Provider store={store}>
<MainApp />
</Provider>
);
}
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
const SomeComponent = () => {
const userToken = useSelector(state => state.userToken);
const dispatch = useDispatch();
return (
<div>
{userToken ? `Logged in with token: ${userToken}` : 'Not logged in'}
</div>
);
};
通过上述方法,你可以有效地在React Native应用程序中传递和管理userToken
。
领取专属 10元无门槛券
手把手带您无忧上云