First, state management has always been a point that we cannot get around. Before, we published a vuex of vUE state management, and this time we published a Redux of React state management. Firstly, we need to understand two points, the first is Actions and the second is reducers. The purpose of Actions is to manage some methods of Redux, and reducer is to manage the trigger conditions of different Actios and write processing logic.

// Actions, define an action: setUserInfo
const setUserInfo = (data) = > {
    return {
        type: actionTypes.SET_USERINFO,
        data
    }
};
export {setUserInfo};
Copy the code

Define a Reducer again

Reducer matches the logic based on the action type
const userInfo = (state = {}, action) = > {
	switch (action.type) {
		case actionTypes.SET_USERINFO:
			return action.data;
		default:
			returnstate; }};Copy the code

Used in components

The first thing we need to do is associate the Reducer with the component/** * the provider is wrapped in the outermost layer, so that all components can obtain the redux state value *
class App extends React.Component {
	render() {
		return (
			//
			<Provider store={store}>
				<Router />
			</Provider>); }}Copy the code

Used in business components


const mapStateToProps = state= > state;

const mapDispatchToProps = dispatch= > ({
	setUserInfo: data= > {
        / / distribute reducerdispatch(setUserInfo(data)); }});Map the state from the Reducer to the props of the component
// Map actions in redux to props for the component
export default connect(
	mapStateToProps,
	mapDispatchToProps
)(Form.create()(Login));

// Trigger the reducer, using props to call the methods in the reducers
this.props.setUserInfo(Object.assign({}, values, { role: { type: 1.name: 'Super Administrator'}}));Copy the code

I haven’t used it in a project yet, but I’ve learned how to use it in open source projects. It’s not perfect, but it’ll make it easier for me to read in the future.