REDUX-React Code Principle Analysis

Goals

The main purpose of react using redux is:
1) Realize concise and unified state maintenance and improve code maintainability;
2) Realize simplicity Dependency injection, avoid repeatedly passing parameters;
Plug Any Data Into Any Component. This is the problem that Redux solves. It gives components direct access to the data they need.
3) Realize automatic rendering.

index.js

Application entry code

import React from'react';
import {render} from'react -dom';
import Counter from'./Counter';
import {Provider} from'react-redux';
import {createStore} from'redux';
< br />const initialState = {
count: 0
};

function reducer(state = initialState, action) {
switch(action.type) {< br /> case'INCREMENT':
return {
count: state.count + 1
};
case'DECREMENT':
return {
count: state.count-1
};
default:
return state;
}
}

/**
* 1) Create a global storage object store and pass in the appropriate reducer.
*/
const store = createStore(reducer);

/**
* 2) Bind the store instance to App
*/

const App = () => (



);

render(, document.getElementById('root'));

Component code< /h2>

import React from'react';
import {connect} from'react-redux';

/**
* The store global object created by index.js will be injected into all In the subordinate object, so here can the dispatch function be used to change the properties.
*/
class Counter extends React.Component {
increment = () => {
//In fact, it calls the dispatch function of the global store object
this. props.dispatch({ type:'INCREMENT' });
}

decrement = () => {
this.props.dispatch({ type:'DECREMENT'} );
}

render() {
return (

Counter




{this.props.count}



)
}
}

//specific Property conversion function
function mapStateToProps(state) {
return {
count: state.count
};
}

//pass The connect method converts the state attribute of the store to the attribute of the cost component
export default connect(mapStateToProps)(Counter);

Leave a Comment

Your email address will not be published.