官方文档
国人教程
总结:
1.store由redux的createStore生成
2.state通过store.getState()获取,本质上一般是一个存储着整个应用状态的对象。
3.action本质上是一个包含着type属性的普通对象
4.reducer本质上是通过dispatch进行触发后通过传给dispatch的action进行判段返回一个对象的函数,此函数返回的对象的就state,aciton对象必须包含一个type属性。
小例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://cdn.bootcss.com/redux/3.5.2/redux.min.js"></script>
</head>
<body>
</body>
<script>
//reducer
function test(state,action){
state=state||{counter:0}
switch(action.type){
case "INCREMENT":
state.counter++;
return state
case "DECREMENT":
state.counter--
return state
case "zcjGood":
state.test=100
return state
}
}
var store=Redux.createStore(test)
//对象参数是action,必需包含type属性
//激活redcuer进行操作
store.dispatch({type:'zcjGood'})
//得到state进行输出
console.log(store.getState())
</script>
combineReducers()
这个方法挺重要的
小例子
我们要两个state
{
//计数器
counter,
//待办事项
todos{
optTime:[],
todoList:[]
}
}
根reducer分别存放着counter,todos,得到根reducer,调用createStore生成store
createStore(reducer, [initialState])
combineReducers(reducers)
combineReducers 辅助函数的作用是,传入多个 reducer 函数作为 value 的 object做为参数,然后合并成一个最终的 reducer 函数,然后就可以对这个 reducer 调用 createStore。这样可以在状态很复杂的情况下,依然不会很乱。
注意加粗的字体,传入combineReducers 辅助函数的reducer函数在通过dispatch进行触发执行回调运行代码时,第一个参数不是整个state,而是键名和state中的对象名相等的对象,也可以认为是这样state.键名
。返回的值就是对应state.键值
的值。
import { combineReducers,createStore } from 'redux'
import counterReducer from './counterReducer.js'
import todosReducer from './todosReducers'
const rootReducer = combineReducers({
/* 键名就是该 reducer 对应管理的 state,值是一个回调函数也就是reducer
例如counterReducer(state.counter,action)
*/
counter: counterReducer,
todos: todosReducer
})
var store=createStore(rootReducer)
counter(./counterReducer.js)一个回调函数,第一个参数是之前的值,第二个参数是action对象(就是传给store.dispatch的函数的对象),返回state.counter的值,如果传来的action.type是increment就是递加state.counter,如果不是则返回之前的state.counter
export default function counterReducer(counter = 0, action) { // 传入的 state 其实是 state.counter
switch (action.type) {
case 'INCREMENT':
return counter + 1 // counter 是值传递,因此可以直接返回一个值
default:
return counter
}
}
再来看一下todos,todos跟counter不一样,counter只是一个单纯的包含一个值的对象,todos是一个由两个数组对象组成的对象,todos中有两个状态需要管理,所以todos应该是通过combineReducers来进行管理两个数组的reducer返回的reducer。
/todosReducers/index.js
import {combineReducers} from 'redux'
import optTimeReducer from './optTimeReducer'
import todoListReducer from './todoListReducer'
const todoReducer=combineReducers({
optTime:optTimeReducer,
todoList:todoListReducer
})
export default todoReducer
/todosReducers/optTimeReducer.js,管理state.todos.optTime
export default function optTimeReducer(optTime=[],aciton){
return aciton.type.includes('TODO')?[...optTime,new Date()]:optTime
}
/todosReducers/todoListReducer.js,管理state.todos.todoList
export default function todoListReducer(todoList=[],aciton){
switch(aciton.type){
case 'ADD_TODO':
return [...todoList,aciton.payload]
default:
return todoList
}
}