希望以下代码用帮助大家理解 Redux 的工作原理.
createStore 函数实现如下:
type StoreListener = () => void;
interface Action {
type: string;
}
interface State {}
function createStore<S extends State, T extends Action>(reducer: (state: S, action: T) => S) {
let state: S = {} as any;
const listeners: StoreListener[] = [];
const getState = () => {
return state;
};
const subscribe = (listener: StoreListener) => {
listeners.push(listener);
const unsubscribe = () => {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
return unsubscribe;
};
const dispatch = (action: T) => {
state = reducer(state, action);
listeners.forEach(listener => listener());
};
dispatch({ type: "" } as T);
return { dispatch, subscribe, getState };
}
使用示例如下:
interface TodoAction extends Action {
todo: Todo;
}
interface TodoState extends State {
todos: Todo[];
}
const todoStore = createStore<TodoState, TodoAction>((state, action) => {
if (!action.type) {
const todos = [
new Todo("学习 React", [BuiltinTag.IMPORTANT, BuiltinTag.URGENT]),
new Todo("学习 TypeScript", [BuiltinTag.IMPORTANT]),
new Todo("学习 CSS")
];
return { ...state, todos };
} else {
const todos = state.todos.slice(); // 复制
switch (action.type) {
case TodoActionType.ADD:
todos.push(action.todo);
break;
case TodoActionType.REMOVE:
const index = todos.indexOf(action.todo);
todos.splice(index, 1);
}
return { ...state, todos };
}
});
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.