文章目录
- 1、添加count_action.js
- 1.1、项目结构变化
- 1.2、CODE
- 1.2.1、count_action.js
- 1.2.2、Count_Redux.jsx
- 2、添加constant.js
- 2.1、项目结构变化
- 2.2、CODE
- 2.2.1、constant.js
- 2.2.2、count_action.js
- 2.2.3、count_reducer.js
本示例补全 上一章 redux mini版示例,使用完整版redux完成 求和Demo-redux
1、添加count_action.js
专门用于创建action对象
1.1、项目结构变化
1.2、CODE
1.2.1、count_action.js
/**
* 该文件专门为Count组件生成action对象
*/
/*
function createIncrementAction(data) {
return {
type: 'increment',
data
}
}
function createDecrementAction(data) {
return {
type: 'decrement',
data
}
}
*/
/*******直接简写如下********/
export const createIncrementAction = data => ({ type: 'increment', data })
export const createDecrementAction = data => ({ type: 'decrement', data })
1.2.2、Count_Redux.jsx
import React, { Component } from 'react'
// 引入store,用于获取redux中维护的状态
import store from '../../redux/store'
// 引入actionCreator,专门用于创建action对象
import { createIncrementAction, createDecrementAction } from '../../redux/count_action'
export default class Count extends Component {
state = {
num: 1
}
componentDidMount() {
// 监测redux的状态,变化触发render
store.subscribe(() => {
// redux状态改变就会调这个回调
this.setState({})
})
// 注:这个监测可挂在入口文件上,这样就不用每个组件都写一遍了
}
add = () => {
const { num } = this.state
store.dispatch(createIncrementAction(num))
}
sub = () => {
const { num } = this.state
store.dispatch(createDecrementAction(num))
}
oddAdd = () => {
const { num } = this.state
if (store.getState() % 2 === 1) {
store.dispatch(createIncrementAction(num))
}
}
asyncAdd = () => {
const { num } = this.state
setTimeout(() => {
store.dispatch(createIncrementAction(num))
}, 2000)
}
render() {
//无变化,略...
}
}
2、添加constant.js
专门用于定义action.type常量
2.1、项目结构变化
2.2、CODE
2.2.1、constant.js
/**
* action.type常量
*/
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
2.2.2、count_action.js
/**
* 该文件专门为Count组件生成action对象
*/
import { INCREMENT, DECREMENT } from './constant'
export const createIncrementAction = data => ({ type: INCREMENT, data })
export const createDecrementAction = data => ({ type: DECREMENT, data })
2.2.3、count_reducer.js
/**
* 1、该文件是为了创建一个为Count组件服务的reducer
* reducer本质就是一个函数
* 2、reducer会接到两个参数
* - preState:之前的状态
* - action:动作对象
*/
import { INCREMENT, DECREMENT } from './constant'
export default function countReducer(preState = 0, action) {
// 从action中获取type/data
const { type, data } = action
// 根据type判断如何加data
switch (type) {
case INCREMENT: // +
return preState + data
case DECREMENT: // -
return preState - data
default:
return preState
}
}