redux、action与reducer的拆分与合并
redux
一、在redux中所有的数据均储存于store中,store类似于一颗state树,store是只读属性,也就是只能通过store.getState().xx对其中某个熟性进行读取or store.getState()对所有store数据进行读取简单来讲,redux的一个显著特点是一个应用只提供一个store,在redux中所有的state均储存于同一颗对象树中,即为store,store可通过reducer进行创造
redux两大核心即为action与reducer,action用于描述事件,比如用户干了什么。reducer用于根据需求对store树进行数据修改
store中的数据可在任何地方通过store.getState()进行获取,前提是需要import引入store
二、redux生命周期如下view—>action—>store—>reducer—>view
首先,调用store.dispatch(action)——可以在任何地方调用,例如组件、点击事件、异步请求回调中、定时器等。action主要用于描述当前具体发生事件的对象。 其次store调用reducer对store进行修改,reducer通过action的type类型来寻找对应对函数事件来对store树进行数据更改。需要注意的是每一次操作结束后都需要将state返回出去用于对下一次数据修改的参考 为什么每一次都要返回state呢?主要用于如果无法找到对应type类型对操作就将state原封不动返回
三、最后view通过store.subscribe(this.setState({}))进行监听,当store发生变化则从新store.getState()。并渲染
1,num.js(小reducers1)
let date={
num:20
}
export default function age(state=date,action){
switch(action.type){
case 'numadd':
state.num++
return state
break
case 'numcdd':
state.num--
return state
break
default:
return state
}}
2,age.js(小reducers2)
let date={
age:20
}
export default function age(state=date,action){
switch(action.type){
case 'ageadd':
state.age++
return state
break
case 'agecdd':
state.age--
return state
break
default:
return state
}}
3,index.js(将所有小reducers合并)
import {combineReducers} from 'redux'
import counter from './counter'
import age from './todos'
export default combineReducers({
age,counter
})
4,mystore.js(store仓库)
import {createStore} from 'redux'
import reducer from './index'
const store=createStore(reducer)
export default store
5,App.js(react项目对store数据进行引用与修改)
componentDidMount(){
store.dispatch({
type:'numadd'
})
store.dispatch({
type:'ageadd'
})
console.log(store.getState().age)
}