一、以下是对react-reudx的理解,和工作流程图(如果已有了解直接跳过看实现代码)
React Redux是一个用于管理应用程序状态的库,它结合了React和Redux两个流行的JavaScript库。
React是一个用于构建用户界面的库,它通过将界面拆分成可重用的组件来提高开发效率和代码可维护性。然而,随着应用规模的增长,状态管理变得更加困难。
Redux是一个独立的状态管理库,它使用单一的全局状态树来管理应用程序的状态,并通过纯函数来处理状态的变化。Redux遵循一种称为"Flux"架构的模式,其中包含动作(Action)触发状态变化,状态变化被存储在一个中央存储(Store)中,然后在需要时被应用程序的不同部分使用。
React Redux通过将React组件与Redux状态管理相结合,提供了一种在React应用程序中管理状态的方式。它通过提供特定的组件(如Provider和Connect)来连接Redux store和React组件,并使组件能够从store中获取状态并对其进行更新。
使用React Redux,你可以将应用程序状态统一管理,避免状态散落在各个组件之间导致的混乱。它还提供了一种数据流的机制,使得状态变化可以被追踪和调试,方便排查错误。
总而言之,React Redux通过将React和Redux结合起来,提供了一种强大的状态管理解决方案,使得开发大型React应用程序更加高效和可维护。
1:react-reudx:首先创建一个redux文件夹然后创建一个store.js
从 reudx 中 引入createStore用于创建store对象,引入applyMiddleware
用于支持异步操作,引入 reudcer处理数据,引入 thunk中间件,最后暴露创建的sotre
然后在入口文件中从 react-reudx 中引入 Provider 包裹住跟组件,然后引入store ,传递给 Provider,这样跟组件下的所有组件都就可以获取到数据了
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:模块化开发正式开始第一步:在reudx文件夹中创建一个reducers文件夹,然后创建一个index.js文件用于合并reudcer,index.js中从 redux中引入 combineReducers 用于合并引入的多个ruducer模块,然后引入其他的reducer模块进行合并,模块化开发
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.创建一个count.js Reducer文件为count组件服务reducer的本质就是一个纯函数
2.创建一个person.js Reducer文件为person组件服务reducer的本质就是一个纯函数
命名reducer函数为countReducer()接收两个参数,分别为:之前的状态(preState),动作对象(action),然后 从action中 导出,类型和数据,再写一个 switch判断type类型进行匹配数据的操作
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:第三步在reudx文件夹中创建action文件夹,目的为组件处理异步操作,然后派发给reudcer进行加工处理,几个reducer模块,就创建几个action文件,以下是两个action行为对象文件,count.js专门为count组件生成的action行为对象,person.js专门为person组件生成的action对象
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:第四步就是容器组件和UI组件:react-redux和reudx不一样,reudx组件可以直接和store仓库进行通信,而react-redux中UI组件不可以和store仓库直接通信,需要通过容器组件给store仓具通信,UI组件不能直接和store通信,需要通过容器组件,也可以理解为父组件,高阶组件,UI组件中不做逻辑操作,只做渲染,逻辑操作都在容器组件,借助 connect链接UI组件和容器组件,两个括号第一个括号接收两个参数也是函数,mapStateToProps,接收store中的数据,mapDispatchToProps接收store中的方法,第二个括号包裹UI组件。
第一个括号两个参数函数也可以省略,直接接收store中state数据和方法,
省略mapDispatchToProps后,react-redux帮助我们dispatch
然后传递给UI组件,UI组件通过props接收数据和方法。
例如:容器组件中接收到了一个increment加的方法传递给Ui组件,UI组件通过props接收并触发此方法,然后这个increment方法就会携带数据去action文件中查找相对应的方法,匹配到之后dispatch携带type类型和数据,派发给 store仓库,store不做停留直接传递给reducer函数进行type匹配条件然后数据加工处理,
count.jsx组件
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>
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
<button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>
<button onClick={this.incrementAsync}>异步加</button>
</div>
)
}
}
//使用connect()()创建并暴露一个Count的容器组件
export default connect(
state => ({
count:state.count,
personCount:state.persons.length
}),
{increment,decrement,incrementAsync}
)(Count)
person.jsx组件
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)
总结:
-
Redux是一个独立的状态管理库,它使用单一的全局状态树来管理应用程序的状态,并通过纯函数来处理状态的变化。Redux提供了一套API和机制,包括store、action、reducer等,用于管理数据流和状态变化。
-
React Redux是Redux在React中的绑定库。它提供了用于将Redux与React组件集成的额外功能和工具。React Redux提供了connect函数和Provider组件,让我们可以在React组件中连接到Redux store并获取状态,同时还提供了一些优化性能的机制。
-
最本质的区别:redux和react-redux区别就是 reudx 需要一次一次的从 store中获取数据
store.getState() store.dispatch(createDecrementAction(value*1))