基本概念:
1)redux中的核心中store,store中的放有state,单一数据源,状态只能来源于仓库。
2)state是只读的,你只能获取状态,你不能暴力地去修改仓库中的状态
3)store state reducer action
4)dispatch subscrbe getState
创建仓库:
<script src="./js/redux.js"></script> 相当于在页面中引入Redux。
在Redux这个对象上,有一个api,叫createStore,调用它,就可以创建一个仓库。
使用仓库:
dispatch subscrbe getState
action:
本质就是一个JS对象,这个对象中需要有一个属性,叫type,用来描述一个动作。
reducer:
本质是一个函数,纯函数,根据不同的action和上一次的状态,返回一个新的状态
function reducer(state=initState, action){
switch(action.type){
case "INCREMENT":
return { number:state.number+1 }
case "DECREMENT":
return { number:state.number-1 }
default:
return state
}
}
学习redux,需要站在两个角度:
1)如何去创建仓库(使用craeteStore,准备reducer,准备action,准备初始化状态)
2)如何去使用仓库(3个api)
dispath:用于派发一个action
getState:获取最新状态(状态只能从仓库中获取)
subscribe:订阅 一旦订阅了,当仓库中状态发生了改变,就会执行你订阅的函数,在这个函数中你就可以做一些你想做的事情。
启用redux调试(放在仓库上边)
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
调用composeEnhancers()
let store = Redux.createStore(reducer,composeEnhancers())
action 和 action creator
action:
本质是一个对象,是用来描述一个动作的。它里必须要有一个type属性。
let increment = { type : "INCREMENT" }
let decrement = { type : "DECREMENT" }
action creator:
本质是一个函数,这个函数的返回值是一个action。
function increment(payload){
return { type:"INCREMENT",payload:payload }
}
function decrement(payload){
return { type:"DECREMENT",payload:payload }
}
对于初始化状态:
1)可以在声明reudcer时指定
2)在创建仓库时,也可以指定初始化状态
在脚手架中使用redux
合并管理员
import { combineReducers } from "redux"
import counter from "./counter"
import todos from "./todos"
// reducer就是把两个reducer合并成了一个reducer
let reducer = combineReducers({
counter,
todos
})
export default reducer; // 导出合并后的reducer
在createStore内部会直接调用dispatch