
//npm init
//npm install redux
//1 导入redux(不能通过es6的方式)
// commonjs一种 -> node.jsconst redux = require('redux')const initialState = {counter: 0
}
// reducer
function reducer(state = initialState, action) {switch(action.type) {case "INCREMENT":return { ...state, counter: state.counter + 1 }case "DECREMENT":return { ...state, counter: state.counter - 1 }case "ADD_NUMBER":return { ...state, counter: state.counter + action.num }case "SUB_NUMBER":return { ...state, counter: state.counter - action.num }default:return state}
}//store
const store = redux.createStore(reducer)//订阅store的修改
store.subscribe(() => {console.log("state发生了改变", "counter:", store.getState().counter)
})//actions
const action1 = { type: "INCREMENT" }
const action2 = { type: "DECREMENT" }
const action3 = { type: "ADD_NUMBER", num: 5 }
const action4 = { type: "SUB_NUMBER", num: 12 }//派发 action
store.dispatch(action1)
store.dispatch(action2)
store.dispatch(action3)
store.dispatch(action4)


import store from './store/index.js'
import { addAction, subAction, inAction, deAction } from './store/actionCreators.js'store.subscribe(() => {console.log(store.getState())
})store.dispatch(addAction(10))
store.dispatch(subAction(5))store.dispatch(inAction())
store.dispatch(deAction())
actionCreator.js
import { ADD_NUMBER, SUB_NUMBER, INCREMENT, DECREMENT } from './constants.js'export const addAction = (num) => {return {type: ADD_NUMBER,num,}
}
export const subAction = (num) => {return {type: SUB_NUMBER,num,}
}export const inAction = () => {return {type: INCREMENT,}
}export const deAction = () => {return {type: DECREMENT,}
}
constants.js

export const ADD_NUMBER = "ADD_NUMBER";
export const SUB_NUMBER = "SUB_NUMBER";
export const INCREMENT = "INCREMENT";
export const DECREMENT = "DECREMENT";
index.js

import redux from 'redux'import reducer from './reducer.js'const store = redux.createStore(reducer)export default store
reducer.js

import { ADD_NUMBER, SUB_NUMBER, INCREMENT, DECREMENT } from './constants.js'const defaultState = {counter: 0
}function reducer(state = defaultState, action) {switch(action.type) {case ADD_NUMBER:return { ...state, counter: state.counter + action.num }case SUB_NUMBER:return { ...state, counter: state.counter - action.num }case INCREMENT:return { ...state, counter: state.counter + 1 }case DECREMENT:return { ...state, counter: state.counter - 1 }default:return state}
}export default reducer

在react中引用index.js

上一篇:描述聚会的句子有哪些?
下一篇:描述这条河的句子有哪些