1. redux理解
学习文档:中文文档
- redux是一个专门用于做状态管理的JS库(不是react插件库)
- 它可以用在react,angular,vue等项目中,但基本与react配合使用
- 作用:集中式管理react应用中多个组件共享的状态
2. 什么情况下需要使用redux
- 某个组件的状态,需要让其他组件可以随时拿到(共享)
- 一个组件需要改变另一个组件的状态(通信)
- 总体原则:能不用就不用,如果不用比较吃力才考虑使用
3. redux的动作流程
4. redux的三个核心概念
-
action
- 动作的对象
- 包含2个属性
- type:标识属性,值为字符串,唯一,必要属性
- data:数据属性,值类型任意,可选属性
- 例子:
{type:'ADD_STUDENT',data:{name:'tom',age:18}}
-
reducer
- 用于初始化状态、加工状态
- 加工时,根据旧的state和action,产生新的state的纯函数
-
store
-
将state、action、reducer联系在一起的对象
-
如何得到此对象?
import {createStore} from 'redux'
import reducer from './reducers'
const store = createStore(reducer)
-
此对象的功能:
- getState():得到state
- dispatch(action):分发action,触发reducer调用,产生新的state
- subscribe(listener):注册监听,当产生了新的state时,自动调用
-
5. 求和案例(包含action异步)
- 去除Count组件自身的状态
- 在src下建立redux文件夹,创建store.js和count_reducer.js文件
- store.js:
- 引入redux中的createStore函数,创建一个store
- createStore调用时要传入一个为其服务的reducer
- 暴露store对象
- count_reducer.js:
- reducer的本质是一个函数,接收:preState,action,返回加工后的状态
- reducer有两个作用:初始化状态,加工状态
- reducer被第一次调用时,是store自动触发的,传递的preState是:undefined,传递的action是:类似于
{type:'@@REDUX/INIT_a.2b.4'}
- 在index.js中检测store中状态的改变,一旦改变重新渲染
<App/>
- 注意:redux只负责管理状态,至于状态的改变驱动着页面的展示,要靠自己写
- count_action.js 专门用于创建action对象
- constant.js 防止由于编码疏忽写错action中的type
- 异步action:
- 明确:延迟的动作不想交给组件自身,想交给action
- 何时需要异步action:想要对状态进行操作,但是具体的数据靠异步任务返回
- 具体编码:
yarn add redux-thunk
,并配置在store中- 创建action的函数不再返回一般对象,而是一个函数,该函数写异步任务
- 异步任务有结果后,分发一个同步的action去真正操作数据
- 注意:异步action不是必须要写的,完全可以自己等待异步任务的结果了再去分发同步action
App.jsx
import React, { Component } from 'react'
import Count from './components/Count'
export default class App extends Component {
render() {
return (
<div>
<Count />
</div>
)
}
}
index.js
// 引入react核心库
import React from 'react'
// 引入ReactDOM
import ReactDOM from 'react-dom'
// 引入App组件
import App from './App'
import store from './redux/store'
// 渲染App到页面
ReactDOM.render(<App />, document.getElementById('root'))
store.subscribe(() => {
ReactDOM.render(<App />, document.getElementById('root'))
})
redux/store.js
// 该文件专门用于暴露一个store对象,整个应用只有一个store对象
// 引入createStore,专门用于创建redux中最为核心的store对象
import { createStore, applyMiddleware } from 'redux'
// 引入为Count组件服务的reducer
import countReducer from './count_reducer'
// 引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
// 暴露store
export default createStore(countReducer, applyMiddleware(thunk))
redux/count_action.js
// 该文件专门为Count组件生成action对象
import { INCREMENT, DECREMENT } from './constant'
// import store from './store'
// export function createIncrementAction(data) {
// return { type: 'increment', data }
// }
// export function createDecrementAction(data) {
// return { type: 'decrement', data }
// }
// 同步action(返回的是Object类型的一般对象)
export const createIncrementAction = (data) => ({ type: INCREMENT, data })
export const createDecrementAction = (data) => ({ type: DECREMENT, data })
// 异步action(返回的是函数),异步action一般都会调用同步action,异步action不是必须要用的
export const createIncrementAsyncAction = (data, time) => {
return () => {
setTimeout((dispatch) => {
dispatch(createIncrementAction(data))
}, time)
}
}
redux/count_reducer.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(preState, action)
// 从action对象中获取:type,data
const { type, data } = action
// 根据type决定如何加工数据
switch (type) {
case INCREMENT:
return preState + data
case DECREMENT:
return preState - data
default:
return preState
}
}
redux/constant.js
// 该模块用于定义action对象中type类型的常量值,便于管理
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
components/Count/index.jsx
import React, { Component } from 'react'
// 引入store,用于获取redux中保存状态
import store from '../../redux/store.js'
// 引入actionCreator,专门用于创建action对象
import { createDecrementAction, createIncrementAction, createIncrementAsyncAction } from '../../redux/count_action.js'
export default class Count extends Component {
state = { carName: '奔驰' }
/*
componentDidMount(){
// 检测redux中状态的变化,只要变化,就调用render
store.subscribe(()=>{
this.setState({})
})
}
*/
// 加法
increment = () => {
const { value } = this.selectNumber
// 通知redux加value
store.dispatch(createIncrementAction(value * 1))
}
// 减法
decrement = () => {
const { value } = this.selectNumber
store.dispatch(createDecrementAction(value * 1))
}
// 奇数再加
incrementIfOdd = () => {
const { value } = this.selectNumber
const count = store.getState()
if (count % 2 !== 0) {
store.dispatch(createIncrementAction(value * 1))
}
}
// 异步action加
incrementAsync = () => {
const { value } = this.selectNumber
// setTimeout(() => {
store.dispatch(createIncrementAsyncAction(value * 1, 500))
// }, 500)
}
render() {
return (
<div>
<h3>当前求和为:{store.getState()}</h3>
<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>
)
}
}
6. react-redux
7. 求和案例react-redux的基本使用
- 明确概念:
- UI组件:不能使用任何redux的api,只负责页面的呈现、交互等。
- 容器组件:负责和redux通信,将结果交给UI组件
- 如何创建一个容器组件——靠react-redux的connect函数
- connect(mapStateToProps,mapDispatchToProps)(UI组件)
- mapStateToProps:映射状态,返回值是一个对象
- mapDispatchToProps:映射操作状态的方法,返回值是一个对象
- connect(mapStateToProps,mapDispatchToProps)(UI组件)
- 注意1:容器组件中的store是靠props传进去的,而不是在容器组件中直接引入
- 注意2:mapDispatchToProps也可以是一个对象
App.jsx
import React, { Component } from 'react'
import Count from './containers/Count'
import store from './redux/store'
export default class App extends Component {
render() {
return (
<div>
{/* 给容器组件传递store */}
<Count store={store} />
</div>
)
}
}
index.js
// 引入react核心库
import React from 'react'
// 引入ReactDOM
import ReactDOM from 'react-dom'
// 引入App组件
import App from './App'
import store from './redux/store'
// 渲染App到页面
ReactDOM.render(<App />, document.getElementById('root'))
// 监测redux状态的改变,如redux的状态发生了改变,那么重新渲染App组件
store.subscribe(() => {
ReactDOM.render(<App />, document.getElementById('root'))
})
containers/Count容器组件/index.jsx
// 引入Count的UI组件
import CountUI from '../../components/Count'
// 引入action
import { createIncrementAction, createDecrementAction, createIncrementAsyncAction } from '../../redux/count_action'
// 引入connect用于连接UI组件与redux
import { connect } from 'react-redux'
/*
1.mapStateToProps函数返回的是一个对象
2.返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value
3.mapStateToProps用于传递状态
*/
function mapStateToProps(state) {
return { count: state }
}
/*
1.mapDispatchToProps函数返回的是一个对象
2.返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value
3.mapDispatchToProps用于传递操作状态的方法
*/
function mapDispatchToProps(dispatch) {
return {
jia: (number) => {
// 通知redux执行加法
dispatch(createIncrementAction(number))
},
jian: (number) => {
// 减法
dispatch(createDecrementAction(number))
},
jiaAsync: (number, time) => {
// 异步加
dispatch(createIncrementAsyncAction(number, time))
},
}
}
// 使用connec()()创建并暴露一个Count的容器组件
export default connect(mapStateToProps, mapDispatchToProps)(CountUI)
components/Count UI组件/index.jsx
import React, { Component } from 'react'
export default class Count extends Component {
// 加法
increment = () => {
const { value } = this.selectNumber
this.props.jia(value * 1)
}
// 减法
decrement = () => {
const { value } = this.selectNumber
this.props.jian(value * 1)
}
// 奇数再加
incrementIfOdd = () => {
const { value } = this.selectNumber
if (this.props.count % 2 !== 0) {
this.props.jia(value * 1)
}
}
// 异步加
incrementAsync = () => {
const { value } = this.selectNumber
this.props.jiaAsync(value * 1, 500)
}
render() {
// console.log('UI组件接收到的props', this.props)
return (
<div>
<h3>当前求和为:{this.props.count}</h3>
<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>
)
}
}
redux/store.js
// 该文件专门用于暴露一个store对象,整个应用只有一个store对象
// 引入createStore,专门用于创建redux中最为核心的store对象
import { createStore, applyMiddleware } from 'redux'
// 引入为Count组件服务的reducer
import countReducer from './count_reducer'
// 引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
// 暴露store
export default createStore(countReducer, applyMiddleware(thunk))
redux/constant.js
// 该模块用于定义action对象中type类型的常量值,便于管理
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
redux/count_action.js
// 该文件专门为Count组件生成action对象
import { INCREMENT, DECREMENT } from './constant'
// import store from './store'
// export function createIncrementAction(data) {
// return { type: 'increment', data }
// }
// export function createDecrementAction(data) {
// return { type: 'decrement', data }
// }
// 同步action(返回的是Object类型的一般对象)
export const createIncrementAction = (data) => ({ type: INCREMENT, data })
export const createDecrementAction = (data) => ({ type: DECREMENT, data })
// 异步action(返回的是函数),异步action一般都会调用同步action,异步action不是必须要用的
export const createIncrementAsyncAction = (data, time) => {
return (dispatch) => {
setTimeout(() => {
dispatch(createIncrementAction(data))
}, time)
}
}
redux/count_reducer.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(preState, action)
// 从action对象中获取:type,data
const { type, data } = action
// 根据type决定如何加工数据
switch (type) {
case INCREMENT:
return preState + data
case DECREMENT:
return preState - data
default:
return preState
}
}
8. 求和案例react-redux优化
-
容器组件和UI组件整合成一个文件
-
无需自己给容器组件传递store,给
<App/>
包裹一个<Provider store={store}
即可 -
使用了react-redux后不用自己监测redux中状态的改变了,容器组件可以自动完成这个工作
-
mapDispatchToProps也可以简单的写成一个对象
-
一个组件要和redux通信要经过哪几步?
-
定义好UI组件-----不暴露
-
引入connect生成一个容器组件,并暴露,写法:
connect( state => ({key: value}), //映射状态 {key: xxxAction} //映射操作状态的方法 )(UI组件)
-
在UI组件中通过
this.props.xxx
读取和操作状态
-
App.jsx
import React, { Component } from 'react'
import Count from './containers/Count'
export default class App extends Component {
render() {
return (
<div>
<Count />
</div>
)
}
}
index.js
// 引入react核心库
import React from 'react'
// 引入ReactDOM
import ReactDOM from 'react-dom'
// 引入App组件
import App from './App'
import store from './redux/store'
import { Provider } from 'react-redux'
// 渲染App到页面
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
container/Count/index.jsx
import React, { Component } from 'react'
// 引入action
import { createIncrementAction, createDecrementAction, createIncrementAsyncAction } from '../../redux/count_action'
// 引入connect用于连接UI组件与redux
import { connect } from 'react-redux'
// // 映射状态
// const mapStateToProps = (state) => ({ count: state })
// // 映射操作状态的方法
// const mapDispatchToProps = (dispatch) => ({
// jia: (number) => {
// // 通知redux执行加法
// dispatch(createIncrementAction(number))
// },
// jian: (number) => {
// // 减法
// dispatch(createDecrementAction(number))
// },
// jiaAsync: (number, time) => {
// // 异步加
// dispatch(createIncrementAsyncAction(number, time))
// },
// })
// 定义UI组件
class Count extends Component {
// 加法
increment = () => {
const { value } = this.selectNumber
this.props.jia(value * 1)
}
// 减法
decrement = () => {
const { value } = this.selectNumber
this.props.jian(value * 1)
}
// 奇数再加
incrementIfOdd = () => {
const { value } = this.selectNumber
if (this.props.count % 2 !== 0) {
this.props.jia(value * 1)
}
}
// 异步加
incrementAsync = () => {
const { value } = this.selectNumber
this.props.jiaAsync(value * 1, 500)
}
render() {
// console.log('UI组件接收到的props', this.props)
return (
<div>
<h3>当前求和为:{this.props.count}</h3>
<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>
)
}
}
// 使用connec()()创建并暴露一个Count的容器组件
export default connect(
(state) => ({ count: state }),
//mapDispatchToProps的一般写法
/*(dispatch) => ({
jia: (number) => {
// 通知redux执行加法
dispatch(createIncrementAction(number))
},
jian: (number) => {
// 减法
dispatch(createDecrementAction(number))
},
jiaAsync: (number, time) => {
// 异步加
dispatch(createIncrementAsyncAction(number, time))
},
})*/
// mapDispatchToProps的简写方式
{
jia: createIncrementAction,
jian: createDecrementAction,
jiaAsync: createIncrementAsyncAction,
}
)(Count)
redux文件夹不更改。
9. react-redux数据共享版
- 定义一个Person组件,和Count组件通过redux共享数据
- 为Person组件编写:reducer、action配置,配置constant常量
- Person的reducer和Count的Reducer要使用combineReducers进行合并,合并后的总状态是一个对象
- 交给store的是总reducer,最后注意在组件中取出状态的时候,记得”取到位“
App.jsx
import React, { Component } from 'react'
import Count from './containers/Count'
import Person from './containers/Person'
export default class App extends Component {
render() {
return (
<div>
<Count />
<hr />
<Person />
</div>
)
}
}
index.js
// 引入react核心库
import React from 'react'
// 引入ReactDOM
import ReactDOM from 'react-dom'
// 引入App组件
import App from './App'
import store from './redux/store'
import { Provider } from 'react-redux'
// 渲染App到页面
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
container/Count组件/index.jsx
import React, { Component } from 'react'
// 引入action
import { createIncrementAction, createDecrementAction, createIncrementAsyncAction } from '../../redux/actions/count'
// 引入connect用于连接UI组件与redux
import { connect } from 'react-redux'
// 定义UI组件
class Count extends Component {
// 加法
increment = () => {
const { value } = this.selectNumber
this.props.jia(value * 1)
}
// 减法
decrement = () => {
const { value } = this.selectNumber
this.props.jian(value * 1)
}
// 奇数再加
incrementIfOdd = () => {
const { value } = this.selectNumber
if (this.props.count % 2 !== 0) {
this.props.jia(value * 1)
}
}
// 异步加
incrementAsync = () => {
const { value } = this.selectNumber
this.props.jiaAsync(value * 1, 500)
}
render() {
return (
<div>
<h3>我是Count组件,下方组件总人数为:{this.props.renshu}</h3>
<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>
)
}
}
// 使用connec()()创建并暴露一个Count的容器组件
export default connect(
(state) => ({ count: state.he, renshu: state.rens.length }),
{
jia: createIncrementAction,
jian: createDecrementAction,
jiaAsync: createIncrementAsyncAction,
}
)(Count)
container/Person组件/index.jsx
import React, { Component } from 'react'
import { nanoid } from 'nanoid'
import { connect } from 'react-redux'
import { createAddPersonAction } from '../../redux/actions/person'
class Person extends Component {
addPerson = () => {
const name = this.nameNode.value
const age = this.ageNode.value
const personObj = { id: nanoid(), name, age }
this.props.jiaYiRen(personObj)
this.nameNode.value = ''
this.ageNode.value = ''
}
render() {
return (
<div>
<h3>我是Person组件,上方组件求和为:{this.props.he}</h3>
<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.yiduiren.map((p) => {
return (
<li key={p.id}>
{p.name}---{p.age}
</li>
)
})}
</ul>
</div>
)
}
}
export default connect(
(state) => ({ yiduiren: state.rens, he: state.he }), //映射状态
{ jiaYiRen: createAddPersonAction } //映射操作状态的方法
)(Person)
redux/store.js
// 该文件专门用于暴露一个store对象,整个应用只有一个store对象
// 引入createStore,专门用于创建redux中最为核心的store对象
import { createStore, applyMiddleware, combineReducers } from 'redux'
// 引入为Count组件服务的reducer
import countReducer from './reducers/count'
// 引入为Person组件服务的reducer
import personReducer from './reducers/person'
// 引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
// 汇总所有的reducer变为一个总的reducer
const allReducer = combineReducers({
he: countReducer,
rens: personReducer,
})
// 暴露store
export default createStore(allReducer, applyMiddleware(thunk))
redux/constant.js
// 该模块用于定义action对象中type类型的常量值,便于管理
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
export const ADD_PERSON = 'add_person'
在redux下分别建立actions,reducers文件夹
redux/actions/count.js
// 该文件专门为Count组件生成action对象
import { INCREMENT, DECREMENT } from '../constant'
// 同步action(返回的是Object类型的一般对象)
export const createIncrementAction = (data) => ({ type: INCREMENT, data })
export const createDecrementAction = (data) => ({ type: DECREMENT, data })
// 异步action(返回的是函数),异步action一般都会调用同步action,异步action不是必须要用的
export const createIncrementAsyncAction = (data, time) => {
return (dispatch) => {
setTimeout(() => {
dispatch(createIncrementAction(data))
}, time)
}
}
redux/actions/person.js
import { ADD_PERSON } from '../constant'
// 创建增加一个人的action动作对象
export const createAddPersonAction = (personObj) => ({ type: ADD_PERSON, data: personObj })
redux/reducers/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) {
// 从action对象中获取:type,data
const { type, data } = action
// 根据type决定如何加工数据
switch (type) {
case INCREMENT:
return preState + data
case DECREMENT:
return preState - data
default:
return preState
}
}
redux/reducers/person.js
import { ADD_PERSON } from '../constant'
// 初始化人的列表
const initState = [{ id: '001', name: 'tom', age: 18 }]
export default function personReducer(preState = initState, action) {
const { type, data } = action
switch (type) {
case ADD_PERSON: //若添加一个人
// preState.unshift(data) //此处不可以这样写,这样会导致preState被改写了,personReducer就不是纯函数了
return [data, ...preState]
default:
return preState
}
}
10.纯函数
- 一类特别的函数:只要是同样的输入(实参),必定得到同样的输出(返回)
- 必须遵守一下约束:
- 不得改写参数数据
- 不会产生任何副作用,例如网络请求,输入和输出设备
- 不能调用Date.now()或者Math.random()等不纯的方法
- redux的reducer函数必须是一个纯函数
11. react-redux开发者工具的使用
yarn add redux-devtools-extension
- store中进行配置
import {composeWithDevTools} from 'redux-devtools-extension'
const store = createStore(allReducer,composeWithDevTools(applyMiddleWare(thunk)))
12. react-redux写法规范版
App.jsx
import React, { Component } from 'react'
import Count from './containers/Count' //引入的Count容器组件
import Person from './containers/Person' //引入的Person容器组件
export default class App extends Component {
render() {
return (
<div>
<Count />
<hr />
<Person />
</div>
)
}
}
index.js
// 引入react核心库
import React from 'react'
// 引入ReactDOM
import ReactDOM from 'react-dom'
// 引入App组件
import App from './App'
import store from './redux/store'
import { Provider } from 'react-redux'
// 渲染App到页面
ReactDOM.render(
// 此处需要用Provider包裹App,目的是让App所有的后代容器组件都能接收到store
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
redux/store.js
// 该文件专门用于暴露一个store对象,整个应用只有一个store对象
// 引入createStore,专门用于创建redux中最为核心的store对象
import { createStore, applyMiddleware } from 'redux'
// 引入汇总之后的reducer
import reducer from './reducers'
// 引入redux-devtools-extension
import { composeWithDevTools } from 'redux-devtools-extension'
// 引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
// 暴露store
export default createStore(reducer, composeWithDevTools(applyMiddleware(thunk)))
redux/constant.js
// 该模块用于定义action对象中type类型的常量值,便于管理
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
export const ADD_PERSON = 'add_person'
redux/actions/count.js
// 该文件专门为Count组件生成action对象
import { INCREMENT, DECREMENT } from '../constant'
// 同步action(返回的是Object类型的一般对象)
export const increment = (data) => ({ type: INCREMENT, data })
export const decrement = (data) => ({ type: DECREMENT, data })
// 异步action(返回的是函数),异步action一般都会调用同步action,异步action不是必须要用的
export const incrementAsync = (data, time) => {
return (dispatch) => {
setTimeout(() => {
dispatch(increment(data))
}, time)
}
}
redux/actions/person.js
import { ADD_PERSON } from '../constant'
// 创建增加一个人的action动作对象
export const addPerson = (personObj) => ({ type: ADD_PERSON, data: personObj })
redux/reducers/index.js
// 该文件用于汇总所有的reducer为一个总的reducer
// 引入combinReducers,用于汇总多个reducer
import { combineReducers } from 'redux'
// 引入为Count组件服务的reducer
import count from './count'
// 引入为Person组件服务的reducer
import person from './person'
// 汇总所有的reducer变为一个总的reducer
export default combineReducers({
count,
person,
})
redux/reducers/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) {
// 从action对象中获取:type,data
const { type, data } = action
// 根据type决定如何加工数据
switch (type) {
case INCREMENT:
return preState + data
case DECREMENT:
return preState - data
default:
return preState
}
}
redux/reducers/person.js
import { ADD_PERSON } from '../constant'
// 初始化人的列表
const initState = [{ id: '001', name: 'tom', age: 18 }]
export default function personReducer(preState = initState, action) {
const { type, data } = action
switch (type) {
case ADD_PERSON: //若添加一个人
return [data, ...preState]
default:
return preState
}
}
containers/Count/index.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 {
// 加法
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() {
return (
<div>
<h3>我是Count组件,下方组件总人数为:{this.props.personCount}</h3>
<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>
)
}
}
// 使用connec()()创建并暴露一个Count的容器组件
export default connect(
(state) => ({
count: state.count,
personCount: state.person.length,
}),
{ increment, decrement, incrementAsync }
)(Count)
containers/Person/index.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
const personObj = { id: nanoid(), name, age }
this.props.addPerson(personObj)
this.nameNode.value = ''
this.ageNode.value = ''
}
render() {
return (
<div>
<h3>我是Person组件,上方组件求和为:{this.props.count}</h3>
<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.person.map((p) => {
return (
<li key={p.id}>
{p.name}---{p.age}
</li>
)
})}
</ul>
</div>
)
}
}
export default connect(
(state) => ({
person: state.person,
count: state.count,
}), //映射状态
{ addPerson } //映射操作状态的方法
)(Person)