项目目录
该演示是用node.js加载redux 同学在创建项目的时候先npm init 或者
yarn add -y好像 直接创建出来packge.json
目录/store/index.js
这里文件主要是用来引入redux创建实例:
import redux from 'redux'
// 这个文件是处理action和state
import reducer from './reducer.js'
// 创建store
const store=redux.createStore(reducer)
export default store
目录/store/actionCreators.js
// 创建一个函数告诉reducer你要做什么
export const addAciton=()=>({
type:'ADD_COUNT'
})
目录/store/reducer.js
// reducer个人理解用来处理更新你需要修改的state
const defaultState={
count:0
}
// reducer里面有两个值 state和action
// state是你需要更改的值 我们会默认给state一个默认值
// action是你具体的操作
function reducer(state=defaultState,action){
// swich判断多个的时候更优雅
swich(action.type)
case "ADD_COUNT":
return {...state,count:state.count+1}
default:
return 0 || state
}
export default reducer
目录 scr/index.js
// 相同于你要用的地方
import store from './store/index.js'
import {addAciton} from './store/actionCreators.js'
// 监听state的变化
store.subscibe(()=>{
console.log(store.getState())
})
// 派发
store.dispatch(addAciton)
结果
{ count: 1 }