Today, I want to realize the user login for the first time, the next login free function. Redux: Redux: Redux: Redux: Redux: Redux: Redux: Redux
The components covered in this article are:
- React-redux and Redux (Basic)
- Redux-persist (for caching)
- Redux-thunk (middleware, here using log printing for asynchronous calls)
- Redux-actions (simplified interface calls)
- Redux-logger (Prints logs when data changes in REdux)
The detailed versions used are as follows:
General idea:
Update the reducer on the basic actions + Reducer + store, simplify reducer with redux-actions, add redux-persist in the store to cache the data to be cached, and have whitelist and blacklist functions. Then print the log.
Steps:
- Configure the actions
- Configuration of reducer
- Configure the store
- Import document package
- Page calls
Here is the file structure:
First, configure actions
/** * User token information, involving identity verification in all network requests */
export const USER_TOKEN = 'USER_TOKEN';
/** * user information, USER_TOKEN + USER_INFO have values, * User Information, USER_TOKEN + USER_INFO have values, you can log in without entering the account password again */
export const USER_INFO = 'USER_INFO';
Copy the code
USER_TOKEN is the token issued after login, and USER_INFO is the user information.
2. Configure reducer
/** * Created by supervons on 2019/08/20. Reducer * redux Reducer Settings, use redux-actions to write more reducer */
import { USER_TOKEN, USER_INFO } from '.. /action/userActionTypes';
import { handleActions } from 'redux-actions';
// Initialize the data
const initialState = {
userToken: ' '.userInfo: {}};const handler = {};
handler[USER_TOKEN] = (state, action) = > {
const { userToken } = action;
return {
...state,
userToken
};
};
handler[USER_INFO] = (state, action) = > {
const { userInfo } = action;
return {
...state,
userInfo
};
};
export default handleActions(handler, initialState);
Copy the code
The point here is that in the handler method, we’ve already done the assignment of actions, which is a lot simpler than what we did before.
For more information: redux-actions.js.org
Configure store
The key to the
/** * Created by supervons on 2019/08/20. Add redux-persist to cache data in whitelist (reducer as a unit) * Configure redux and add redux-persist to cache data in whitelist (in reducer) */
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '.. /reducer';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import logger from 'redux-logger';
const middleWares = [thunk];
const persistConfig = {
key: 'root'.// Define the data key
storage, // Select the storage engine
whitelist: ['UserReducer'] // Whitelists in arrays are cached
};
// Encapsulate reducers
const persistedReducer = persistReducer(persistConfig, rootReducer);
/* Global __DEV__ * Development environment adds log output, redux data changes output */
if (__DEV__) {
middleWares.push(logger);
}
export default function configureStore() {
constenhancers = compose(applyMiddleware(... middleWares));const store = createStore(persistedReducer, enhancers);
// Persist store
let persist = persistStore(store, persistedReducer);
return { store, persist };
}
Copy the code
Iv. Import file package
import { Provider } from 'react-redux';
import configureStore from './src/common/redux/store/store';
import { PersistGate } from 'redux-persist/integration/react';
// Import redux and redux-persist configured variables for use
const { store, persist } = configureStore();
const App = () = > {
return (
// The loading in the PersistGate must be a component. Otherwise, a short black screen will occur after the page is started
<Provider store={store}>
<PersistGate loading={null} persistor={persist}>{... }</PersistGate>
</Provider>
);
};
Copy the code
Note: The loading component needs to be configured by itself, otherwise there will be a short grey screen. You can add an Image tag, so that the Image is the boot page, so that the boot page is continued, or a loading loader.
Fifth, page call
class Login extends Component {
componentDidMount(): void {
// Check whether there is data in the redux-persist cache, if there is, fetch direct login
if (this.props.userToken && this.props.userInfo) {
jwtToken = this.props.userToken;
userInfo = this.props.userInfo;
this.props.navigation.replace('MainPage'); }}setToken(){
// Assign a value to store
this.props.setToken('123');
}
{...}
}
// Retrieve data from store
const mapStateToProps = state= > {
return {
userToken: state.UserReducer.userToken,
userInfo: state.UserReducer.userInfo
};
};
/ / Dispatch method
const mapDispatchToProps = dispatch= > {
return {
setToken: userToken= > {
dispatch({ type: USER_TOKEN, userToken: userToken });
},
setUserInfo: userInfo= > {
dispatch({ type: USER_INFO, userInfo: userInfo }); }}; };export default (Login = connect(
mapStateToProps,
mapDispatchToProps
)(Login));
Copy the code
The following idea is simple: after successful login, store the value and check if there is any value in store the next time you enter the login page. If there is any value, fetch it and log in directly (userInfo and jwtToken are set as global variables). If there is no value, log in. Then in the Exit button, clear the value in store for logout.
Finally, a rendering:
- It is recommended to use with realm when the number is too large.
- Not all data needs to be redux, but it is mostly used when data is transferred between sub-pages and across multiple pages.
- Project address: github.com/supervons/E…
Hit star if you like.