本示例修改自 上一章 求和Demo


/*** action.type常量*/
// for Count
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
// for Person
export const ADD_PERSON = 'add_person'
import { ADD_PERSON } from '../constant'// 创建添加一个人信息的动作对象
export const createAddPersonAction = data => ({ type: ADD_PERSON, data })
import { ADD_PERSON } from '../constant'export default function personReducer(preState = [], action) {const { type, data } = actionswitch (type) {case ADD_PERSON:return [data, ...preState]default:return preState}
}
import {// 引入createStore,专门用于创建redux中最为核心的store对象createStore,// 引入applyMiddleware 执行中间件applyMiddleware,// 引入 combineReducers 组合 reducerscombineReducers
} from 'redux'
//引入reducers
import countReducer from './reducers/count'
import personReducer from './reducers/person'
// 引入 redux-thunk 用于支持异步action
import thunk from 'redux-thunk'// 共享就得把 reducer 组合到一起传进去
const allReducers = combineReducers({count: countReducer,people: personReducer
})//暴露store
export default createStore(allReducers, applyMiddleware(thunk))
// import 未改变,略...class Count extends Component {// 方法等都未改变,略...render() {const { count, people } = this.propsreturn (我是Count,下面已经添加了{people.length}个人
{/* 内容全部未变,略... */})}
}// 暴露容器组件
export default connect(state => ({count: state.count,people: state.people}),{// 未改变,略...}
)(Count)
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { nanoid } from 'nanoid'
import { createAddPersonAction } from '../../redux/actions/person'class Person extends Component {state = {name: '',age: '',}submit = () => {this.props.add({id: nanoid(),...this.state})// 清空表单this.setState({name: '',age: ''})}render() {const { name, age } = this.stateconst { people, count } = this.propsreturn (我是Person,上面求和为{count}
name}onChange={e => this.setState({ name: e.target.value })}/>
age}onChange={e => this.setState({ age: e.target.value })}/>
{people.map(i => (- i.id}>{`姓名:${i.name}-年龄:${i.age}`}
))}
)}
}export default connect(state => ({people: state.people,count: state.count}),{add: createAddPersonAction}
)(Person)

*补充:纯函数
- 一类特别的函数: 只要是同样的输入(实参),必定得到同样的输出(返回)
- 必须遵守以下一些约束
- 不得改写参数数据
- 不会产生任何副作用,例如网络请求,输入和输出设备
- 不能调用Date.now()或者Math.random()等不纯的方法
redux的reducer函数必须是一个纯函数