How to use React-Redux

1. Using react-redux in React projects can make it more convenient for you to use redux, the principle is to use a tag nesting when registering the app, .js subcomponents of your app, and pass all the forms to youindex.jsProvideerstateprops

App.js

import React, { Component } from "react";
import About from "./pages/About"; // About is the routing component
import { Provider } from 'react-redux'
import { PersistGate } from 'redux-persist/integration/react'
import store, { persistor } from './store/index'
 
export default class App extends Component {
    render() {
        console.log('store', store)
        return (
            <Provider store={store}>
                <PersistGate loading={null} persistor={persistor}>
                    <About></About>
                </PersistGate>
            </Provider>
        );
    }
}

2. create a store file

createStore: Create a Redux store to hold all the states in your app

applyMiddleware: Middleware, which is used to enhance the methodreduxcreatStore

compose: combinatorial function

redux-persist: used to implement data persistence

store/index.js

import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import { persistStore, persistReducer } from 'redux-persist'
//  Storage mechanism, localStorage, sessionStorage, etc. can be replaced, currently using storage
import storage from 'redux-persist/lib/storage';
import rootReducer from './reducers'
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';
 
const initState = 0
const middleware = [thunk]
 
const persistConfig = {
    key: 'root', // must
    storage: storage, // cache mechanism
    stateReconciler: autoMergeLevel2 // See the 'Merge Process' section for details
}
 
const persistedReducer = persistReducer(persistConfig, rootReducer)
 
const store = createStore(
    persistedReducer,
    initState,
    compose(
        applyMiddleware(...middleware)
    ),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
 
export const persistor = persistStore(store)
 
export default store

4. modules containing the type constant names of n actions, here just to avoid inconsistencies between the variables and the types of actions

constant/types.js

 export const ADD_NUM = 'ADD_NUM'
 
 export const DEL_NUM = 'DEL_NUM'

Creating reducers, Reducers is the work that really implements changes in state data

reducers/numReducer.js

import { ADD_NUM, DEL_NUM } from '../constant/types'
 
const initState = 0
 
const calculate = (state = initState, action) => {
    let payload = action.payload
    switch (action.type) {
        case ADD_NUM:
            state = payload + 1
            return state
        case DEL_NUM:
            state = payload - 1
            return state
        default:
            return state
    }
}
 
export default calculate

The combineReducers helper function works by merging an object consisting of several different reducer functions as value into a final reducer function, and then you can call createStore on this reducer

reducers/index.js

import { combineReducers } from 'redux'
import numReducer from './numReducer'
 
export default combineReducers({ num: numReducer })

configure asynchronous actions

action/numAction.js

import { ADD_NUM, DEL_NUM } from '../constant/types'
 
export const add = item => dispatch => {
    dispatch({
        type: ADD_NUM,
        payload: item
    })
}
 
export const del = item => dispatch => {
    dispatch({
        type: DEL_NUM,
        payload: item
    })
}

applied to components

import React from 'react'
import {connect} from 'react-redux';
import {add, del} from '../../store/action/numAction';
 
 function About(props) {
	 const { add, del, item } = props
	 const test = () => { add(item) }
	 const test1 = () => { del(item) }
		return (
			<div>
             <h3>I am About content</h3>
			 <div>{item}</div>
			 <button onClick={() => test()}>
                add
            </button>
            <button onClick={() => test1()}>
                reduce
            </button>
			</div>
		)
}
 
const mapStateToProps = (state) => {
    return { item: state.num }
}
 
const mapDispatchToProps = (dispatch) => {
    return {
        add(data){ dispatch(add(data)); },
        del(data){ dispatch(del(data)); }
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(About);

Leave a Reply