使用
import {createStore} from 'redux'
const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'add':
return state + 1
case 'minus':
return state - 1
default:
return state
}
}
const store = createStore(
combineReducers({
counter: counterReducer,
}),
applyMiddleware(logger, thunk),
);
export default store
import React, { Component } from "react";
import store from "../store/ReduxStore";
export default class ReduxPage extends Component {
componentDidMount() {
store.subscribe(() => {
this.forceUpdate();
});
}
add = () => {
store.dispatch({ type: "add" });
};
minus = () => {
store.dispatch({ type: "minus" });
};
stayStatic = () => {
store.dispatch({ type: "others" });
};
render() {
console.log("store", store);
return (
<div>
<h1>ReduxPage</h1>
<p>{store.getState()}</p>
<button onClick={this.add}>add</button>
<button onClick={this.minus}>minus</button>
<button onClick={this.stayStatic}>static</button>
</div>
);
}
}
手写版
export function createStore(reducer, enhancer) {
if (enhancer) {
return enhancer(createStore)(reducer);
}
let currentState = undefined;
let currentListeners = [];
function getState() {
return currentState;
}
function dispatch(action) {
currentState = reducer(currentState, action);
currentListeners.map(lis => lis());
return action;
}
function subscribe(listener) {
currentListeners.push(listener);
}
dispatch({ type: "xxxx" });
return {
getState,
dispatch,
subscribe,
};
}
export function applyMiddleware(...middlewares) {
return createStore => (...args) => {
const store = createStore(...args);
const midAPi = {
getState: store.getState,
dispatch: store.dispatch,
};
const middlewareChain = middlewares.map(mw => mw(midAPi));
const dispatch = compose(...middlewareChain)(store.dispatch);
return {
...store,
dispatch,
};
};
}
function compose(...funcs) {
const len = funcs.length;
if (len === 0) {
return arg => arg;
} else if (len === 1) {
return funcs[0];
} else {
return funcs.reduce((a, b) => (...args) => b(a(...args)));
}
}
import { createStore, applyMiddleware } from "../redux";
import { counterReducer } from "./counterReducer";
const store = createStore(counterReducer, applyMiddleware(logger, thunk));
function logger({ dispatch,getState }) {
return dispatch => action => {
action.type && console.log(action.type + "执行啦!");
return dispatch(action);
};
}
function thunk({ dispatch,getState }) {
return dispatch => action => {
if (typeof action === "function") {
return action(dispatch, getState);
} else {
return dispatch(action);
}
};
}
export default store;