Simple use of Redux and react Redux

Time:2021-10-27

A simple case of using Redux in react project

Scaffold create react app

1. Install Redux

npm install redux --save

2. Redux store directory file allocation

--Action.js action

 --Reducers compute property collection folder

        --Index.js calculation module exit

        --User.js calculation module 1

        --Test.js calculation module 2

  --Store.js store exit of Redux

  --Type.js action action name type

Structural case

Simple use of Redux and react Redux

3. Store code

1. Action.js action integration module

import types from '../type.js';
 
//The number of messages to be sent by the view is encapsulated here
 
// 
export const userAction=(data)=>({type:types.USER,data});
 
// 
export const userTokenAction=(data)=>({type:types.TOKEN,data});

2. Type.js constant name category encapsulation

 
export default  {
    TOKEN:'TOKEN',
    USER:'USER',
    USER_NAME:'USER_NAME',
    
}

3. Reducers computing attribute integration

User.js calculation module 1
(PS: whether the JS files of the calculation module are divided into multiple or written into one depends on their own needs. Here, for example, only one is written, and token.js and user.js are consistent)

import { createStore,combineReducers } from 'redux';
import _type from '../type.js';
 
//The reducer function will accept two parameters: the previous state and the action object
Const initstate = 'initialization value';
export default  function User(state = initState ,action){
        const {type,data} =action;
        //Console.log ("trigger _");
        switch(type){
            case _type.USER:
            //It is better to generate new data    
            return {...data};
            case _type.USER_NAME:
            return '111';
            case _type.TOKEN:
            return state + '222';
            default:
            return state;
        }
}

Index.js calculation module exit

import { createStore,applyMiddleware,combineReducers} from 'redux';
import User  from './user'; 
import Token  from './token'; 
 
//Whether to use the combinereducers method to merge multiple reducers depends on your own needs. When using combinereducers to merge, all the calculation methods in combinereducers will be triggered when calling the action method. Therefore, you need to pay attention to the judgment conditions in the calculation method!
const allReducers=combineReducers({
    user:User,
    token:Token,
});
 
export default allReducers;

4. Redux export

import { createStore,applyMiddleware,combineReducers} from 'redux';
import allReducers from './reducers/index';
 
export default createStore(allReducers);//  Create a data warehouse

5. Project entrance integration

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import serviceUrl from  './service/url';
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';
import store from './redux/store';
 
ReactDOM.render(
  <React.StrictMode>
     <Provider store={store}>
       <App />
     </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);
 
reportWebVitals();

4. Use in the page

import React,{component} from 'react';
import './index.scss';
import { Form, Input, Button, Checkbox,message } from 'antd';
import { Row, Col } from 'antd';
import Config from '../../utils/config';
import { HttpRequest,HttpStatus } from '../../service/http';
import Url from '../../service/url';
import md5 from 'js-md5';
import {  Link } from "react-router-dom";
import {connect} from 'react-redux'
import { userTokenAction,userAction } from '../../redux/actions/action';
 
 
 class Login extends React.PureComponent {
    constructor(props){
        super(props);
        
    }
   
    //Call Redux method
    onFinish = (values) => {
        
        this.props.userToken(11111 || null);
        this.props.userAction(22222 || null);
    };  
    
    
    
    render() { 
     return  <div>
        Display the value of Redux store {this. Props?. token | 'no data temporarily'}
 
        < button onclick = {() = > {this. Onfinish}} > trigger Redux method < / button >
     </div>
    
    }
}
 
//Redux store value exposure
const mapStateToProps=(state)=>{
    return {
        token:state.token,
    }
};
 
//Redux method exposure
const mapDispatchToProps = (dispatch) => {
    return {
        userToken:(token)=>{
            dispatch(userTokenAction(token))
        },
        userAction:(data)=>{
            dispatch(userAction(data))
        }
    };
};
export default connect(mapStateToProps, mapDispatchToProps)(Login);

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]