React-Redux state management tool (modular development)

1. The following is the understanding of react-reudx, and the workflow diagram (if you already know it, skip it and see the implementation code)

React Redux is a library for managing application state that combines two popular JavaScript libraries, React and Redux.

React is a library for building user interfaces that improves development efficiency and code maintainability by splitting the interface into reusable components. However, as the application scale grows, state management becomes more difficult.

Redux is an independent state management library that uses a single global state tree to manage the state of the application and handles state changes through pure functions. Redux follows a pattern called "Flux" architecture, which consists of actions (Actions) triggering state changes, state changes are stored in a central store (Store), and then used by different parts of the application when needed.

React Redux provides a way to manage state in React applications by combining React components with Redux state management. It connects Redux store and React components by providing specific components such as Provider and Connect, and enables components to fetch state from the store and update it.

With React Redux, you can manage the application state in a unified way, avoiding the confusion caused by state scattered among various components. It also provides a mechanism for data flow, so that state changes can be tracked and debugged to facilitate troubleshooting.

All in all, React Redux provides a powerful state management solution by combining React and Redux, making developing large React applications more efficient and maintainable.

 1: react-reudx: first create a redux folder and then create a store.js 
import createStore from reudx to create store objects, introduce applyMiddleware
to support asynchronous operations, introduce reudcer to process data, introduce thunk middleware, and finally expose creation The sotre
then introduces Provider from react-reudx in the entry file to wrap the root component, then introduces store and passes it to Provider, so that all components under the root component can get data

store.js

/* 
	该文件专门用于暴露一个store对象,整个应用只有一个store对象
*/

//引入createStore,专门用于创建redux中最为核心的store对象
import {createStore,applyMiddleware} from 'redux'
//引入汇总之后的reducer
import reducer from './reducers'
//引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
//引入redux-devtools-extension
import {composeWithDevTools} from 'redux-devtools-extension'

//暴露store 
export default createStore(reducer,composeWithDevTools(applyMiddleware(thunk)))

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'
import {Provider} from 'react-redux'

ReactDOM.render(
	/* 此处需要用Provider包裹App,目的是让App所有的后代容器组件都能接收到store */
	<Provider store={store}>
		<App/>
	</Provider>,
	document.getElementById('root')
)

2: Modular development officially started Step 1: Create a reducers folder in the reudx folder, and then create an index.js file for merging reudcer, and import combineReducers from redux in index.js for merging multiple imported ruducer module, and then introduce other reducer modules for merging, modular development

index.js

/* 
	该文件用于汇总所有的reducer为一个总的reducer
*/
//引入combineReducers,用于汇总多个reducer
import {combineReducers} from 'redux'
//引入为Count组件服务的reducer
import count from './count'
//引入为Person组件服务的reducer
import persons from './person'

//汇总所有的reducer变为一个总的reducer
export default  combineReducers({
	count,
	persons
})

3: 1. Create a count.js Reducer file to serve the count component. The essence of the reducer is a pure function.
2. Create a person.js Reducer file to serve the person component. The essence of the reducer is a pure function.
Name the reducer function as countReducer() to receive Two parameters, respectively: the previous state (preState), action object (action), and then export the type and data from the action, and then write a switch to determine the type type to match the data

count.js

/* 
	1.该文件是用于创建一个为Count组件服务的reducer,reducer的本质就是一个函数
	2.reducer函数会接到两个参数,分别为:之前的状态(preState),动作对象(action)
*/
import {INCREMENT,DECREMENT} from '../constant'

const initState = 0 //初始化状态
export default function countReducer(preState=initState,action){
	// console.log('countReducer@#@#@#');
	//从action对象中获取:type、data
	const {type,data} = action
	//根据type决定如何加工数据
	switch (type) {
		case INCREMENT: //如果是加
			return preState + data
		case DECREMENT: //若果是减
			return preState - data
		default:
			return preState
	}
}

person.js

import {ADD_PERSON} from '../constant'

//初始化人的列表
const initState = [{id:'001',name:'tom',age:18}]

export default function personReducer(preState=initState,action){
	// console.log('personReducer@#@#@#');
	const {type,data} = action
	switch (type) {
		case ADD_PERSON: //若是添加一个人
			//preState.unshift(data) //此处不可以这样写,这样会导致preState被改写了,personReducer就不是纯函数了。
			return [data,...preState]
		default:
			return preState
	}
}

4: The third step is to create an action folder in the reudx folder. The purpose is to process asynchronous operations for the component, and then dispatch it to the reudcer for processing. Several reducer modules create several action files. The following are two action behavior object files , the action object generated by count.js specially for the count component, and the action object generated by person.js specially for the person component

count-action.js

/* 
	该文件专门为Count组件生成action对象
*/
import {INCREMENT,DECREMENT} from '../constant'

//同步action,就是指action的值为Object类型的一般对象
export const increment = data => ({type:INCREMENT,data})
export const decrement = data => ({type:DECREMENT,data})

//异步action,就是指action的值为函数,异步action中一般都会调用同步action,异步action不是必须要用的。
export const incrementAsync = (data,time) => {
	return (dispatch)=>{
		setTimeout(()=>{
			dispatch(increment(data))
		},time)
	}
}

person-action.js

import {ADD_PERSON} from '../constant'

//创建增加一个人的action动作对象
export const addPerson = personObj => ({type:ADD_PERSON,data:personObj})

5: The fourth step is the container component and UI component: react-redux is different from reudx, the reudx component can communicate directly with the store warehouse, and the UI component in react-redux cannot directly communicate with the store warehouse, it needs to be given by the container component Store warehousing communication, UI components cannot directly communicate with the store, need to go through container components, can also be understood as parent components, high-level components, UI components do not perform logic operations, only rendering, logic operations are all in container components, with the help of connect Link UI components and container components, two brackets The first bracket receives two parameters and is also a function, mapStateToProps receives the data in the store, mapDispatchToProps receives the method in the store, and the second bracket wraps the UI component.
The two parameter functions in the first bracket can also be omitted, directly receive the state data and methods in the store,
after omitting mapDispatchToProps, react-redux helps us dispatch
and then pass it to the UI component, and the UI component receives the data and method through props.
For example: the container component receives an increment method and passes it to the Ui component, the UI component receives and triggers this method through props, and then the increment method will carry the data to find the corresponding method in the action file, and after matching, the dispatch carries The type type and data are dispatched to the store warehouse, and the store directly passes it to the reducer function without stopping to perform type matching conditions and then data processing.

count.jsx component

import React, { Component } from 'react'
//引入action
import {
	increment,
	decrement,
	incrementAsync
} from '../../redux/actions/count'
//引入connect用于连接UI组件与redux
import {connect} from 'react-redux'

//定义UI组件
class Count extends Component {

	state = {carName:'奔驰c63'}

	//加法
	increment = ()=>{
		const {value} = this.selectNumber
		this.props.increment(value*1)
	}
	//减法
	decrement = ()=>{
		const {value} = this.selectNumber
		this.props.decrement(value*1)
	}
	//奇数再加
	incrementIfOdd = ()=>{
		const {value} = this.selectNumber
		if(this.props.count % 2 !== 0){
			this.props.increment(value*1)
		}
	}
	//异步加
	incrementAsync = ()=>{
		const {value} = this.selectNumber
		this.props.incrementAsync(value*1,500)
	}

	render() {
		//console.log('UI组件接收到的props是',this.props);
		return (
			<div>
				<h2>我是Count组件,下方组件总人数为:{this.props.renshu}</h2>
				<h4>当前求和为:{this.props.count}</h4>
				<select ref={c => this.selectNumber = c}>
					<option value="1">1</option>
					<option value="2">2</option>
					<option value="3">3</option>
				</select>&nbsp;
				<button onClick={this.increment}>+</button>&nbsp;
				<button onClick={this.decrement}>-</button>&nbsp;
				<button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>&nbsp;
				<button onClick={this.incrementAsync}>异步加</button>&nbsp;
			</div>
		)
	}
}

//使用connect()()创建并暴露一个Count的容器组件
export default connect(
	state => ({
		count:state.count,
		personCount:state.persons.length
	}),
	{increment,decrement,incrementAsync}
)(Count)

 person.jsx component

import React, { Component } from 'react'
import {nanoid} from 'nanoid'
import {connect} from 'react-redux'
import {addPerson} from '../../redux/actions/person'

class Person extends Component {
	addPerson = ()=>{
		const name = this.nameNode.value
		const age = this.ageNode.value*1
		const personObj = {id:nanoid(),name,age}
		this.props.addPerson(personObj)
		this.nameNode.value = ''
		this.ageNode.value = ''
	}
	render() {
		return (
			<div>
				<h2>我是Person组件,上方组件求和为{this.props.count}</h2>
				<input ref={c=>this.nameNode = c} type="text" placeholder="输入名字"/>
				<input ref={c=>this.ageNode = c} type="text" placeholder="输入年龄"/>
				<button onClick={this.addPerson}>添加</button>
				<ul>
					{
						this.props.persons.map((p)=>{
							return <li key={p.id}>{p.name}--{p.age}</li>
						})
					}
				</ul>
			</div>
		)
	}
}
export default connect(
	state => ({
		persons:state.persons,
		count:state.count
	}),//映射状态
	{addPerson}//映射操作状态的方法
)(Person)

Summarize:

  1. Redux is an independent state management library that uses a single global state tree to manage the state of the application and handles state changes through pure functions. Redux provides a set of APIs and mechanisms, including store, action, reducer, etc., to manage data flow and state changes.

  2. React Redux is a binding library for Redux in React. It provides additional features and tools for integrating Redux with React components. React Redux provides the connect function and Provider components, allowing us to connect to the Redux store and get the state in the React component, and also provides some mechanisms to optimize performance.

  3. The most essential difference: the difference between redux and react-redux is that reudx needs to get data from the store
    store.getState() store.dispatch(createDecrementAction(value*1))

Guess you like

Origin blog.csdn.net/tianyhh/article/details/132322636
Recommended