1. npm install reduce
2. 创建文件
store
- reducer.js
- store.js
- action.js
3. reducer.js
const defaultState ={
key1:value1,
key2:value2
}
export default (state=dafaultState,action)=>{
switch (action.type) {
case "action1":
return function1(state,action.data);
case "action2":
return function2(state, action.data);
default:
return state;
break;
}
}
const function1(state,data){
let newState = JSON.parse(JSON.stringify(state));
return newState
}
4. store.js
import { createStore } from "redux";
import reducer from "./reducer";
const store = createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;
5. action.js
export let Action1= value => {
return {
type: "add1",
value,
};
};
export let Action2= value => {
return {
type: "submit",
value,
};
};
6. 使用
import store from "../../redux/store";
import { Action1} from "../../redux/action";
this.state_g =store.getState()
this.subscribeId = store.subscribe(this.changeStore);
changeStore = () => {
this.state_g = store.getState();
if (this.actived) {
this.forceUpdate();
}
};
store.dispatch(Action1(data))
this.subscribeId()