目录
0.redux脑图
等我学完再做
1.工作流程
2.项目结构
3.源码效果
app.jsx
import React, {Component} from 'react'
import {INCREMENT, DECREMENT} from '../redux/action-types.js'
import * as actions from '../redux/actions'
export default class App extends Component {
increment = () =>{
//1.得到选择,增加数量
const number = this.select.value*1
//2.调用store的方法更新状态
// this.props.store.dispatch({type:INCREMENT,data:number})
this.props.store.dispatch(actions.increment(number))
}
decrement = () =>{
//1.得到选择,增加数量
const number = this.select.value*1
//2.调用store的方法更新状态
// this.props.store.dispatch({type:DECREMENT,data:number})
this.props.store.dispatch(actions.decrement(number))
}
incrementIfOdd = () =>{
//1.得到选择,增加数量
const number = this.select.value*1
//2.得到原本count状态,并计算新count
const count = this.props.store.getState()
//判断满足条件再更新
if(count%2===1){
//3.更新状态
// this.props.store.dispatch({type:INCREMENT,data:number})
this.props.store.dispatch(actions.increment(number))
}
}
incrementAsync = () =>{
//1.得到选择,增加数量
const number = this.select.value*1
//2.得到原本count状态,并计算新count
//启动延时定时器
setTimeout(() => {
//3.更新状态
this.props.store.dispatch(actions.decrement(number))
},1000)
}
render() {
//从外层获取参数
//传结构用const {count},传数值用户= count
const count = this.props.store.getState()
// debugger
return (
<div>
<p>click {count} times</p>
<div>
<select ref={select => this.select =select}>
<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}>increment if odd</button>
<button onClick={this.incrementAsync}>increment async</button>
</div>
</div>
)
}
}
actions.js
/*
action creator模块
*/
import {INCREMENT, DECREMENT} from './action-types'
export const increment = (number) => ({type: INCREMENT,data: number})
export const decrement = (number) => ({type: DECREMENT,data: number})
actions-types.js
/*
Action对象的type常量名称模块
*/
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
reducers.js
/* 包含n个reducer函数的模块 */
import {INCREMENT, DECREMENT} from './action-types'
//指定形参默认值
export function counter(state = 0, action) {
console.log('counter', state, action)
switch (action.type) {
case INCREMENT:
return state + action.data
case DECREMENT:
return state - action.data
default:
return state
}
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app';
import {createStore} from 'redux'
import {counter} from './redux/reducers'
//根据counter函数创建store对象
const store = createStore(counter)//内部会第一次调用reducer函数得到初始state
console.log(store)
//重绘状态
function render(){
ReactDOM.render(<App store={store}/>, document.getElementById('root'))
}
//初始化渲染
render()
//订阅监听(store中的状态变化了,就会自动进行重绘)
store.subscribe(render)
store.js
index.js这部分其实可以拿出来单独作为一个模块