官网:https://redux.js.org/
安装:
npm install redux --save
demo案例:
// redux的使用
import {createStore} from "redux";
// 初始化的时候执行一次 更新数据的时候执行一次
// 第二参数action会接受dispath中传来的type值
const store = createStore( (state = {count: 0}, action) => {
switch(action.type) {
case "INCREMENT":
return {
count: state.count + 1
}
case "DECREMENT":
const decrementBy = typeof action.decrementBy === "number" ? action.decrementBy : null;
if(decrementBy) {
return {
count: state.count - decrementBy
}
}else {
return {
count: state.count - 1
}
}
// 归零
case "RESET":
return {
count: state.count = 0
}
// 设置
case "SET": {
return {
count: action.count
}
}
default:
return state;
}
// if(action.type === "INCREMENT") {
// return {
// count: state.count + 1
// }
// }else{
// return state;
// }
});
// 获取数据
// console.log(store.getState())
// 订阅
store.subscribe(() => {
console.log(store.getState())
})
// dispatch也会执行一次createStore函数
store.dispatch({
type: "DECREMENT",
decrementBy: 10
})
store.dispatch({
type: "DECREMENT"
})
store.dispatch({
type: "DECREMENT"
})
// 获取数据
console.log(store.getState())
store.dispatch({
type: "RESET"
})
// 获取数据
// console.log(store.getState())
store.dispatch({
type: "SET",
count: 1000
})
几个实用的方法:
store.getState() 获取数据
store.subscribe() 订阅推送
store.dispatch() 操作或更新数据和传值