我們今天來改進我們的Todo App
新增todo\src\utils\store.tsx
import React, { createContext, useReducer, Dispatch } from 'react';
export interface ITodo {
id: number,
title: string,
date: string,
done: boolean
};
interface defaultState {
todos: ITodo[];
};
const initState: defaultState = {
todos: [],
};
export enum TodosActionType {
TodosAddItem,
TodosRemoveItem,
TodosFetchAllItem
}
interface TodosAddItem {
type: TodosActionType.TodosAddItem;
payload: ITodo;
}
interface TodosRemoveItem {
type: TodosActionType.TodosRemoveItem;
payload: ITodo;
}
interface TodosFetchAllItem {
type: TodosActionType.TodosFetchAllItem;
payload: ITodo[];
}
type TodosActions = TodosAddItem | TodosRemoveItem | TodosFetchAllItem;
export const StoreCtx = createContext<{
state: defaultState;
dispatch: React.Dispatch<TodosActions>;
}>({
state: initState,
dispatch: () => undefined,
});
const reducer = (state: defaultState, action: TodosActions): defaultState => {
switch (action.type) {
case TodosActionType.TodosAddItem: {
}
case TodosActionType.TodosRemoveItem: {
}
case TodosActionType.TodosFetchAllItem: {
}
default:
return state;
}
};
interface Props {
children: React.ReactNode;
}
export const StoreProvider: React.FC<Props> = ({children}) => {
const [state, dispatch] = useReducer(reducer, initState);
return (
<StoreCtx.Provider value={{ state, dispatch }}>
{children}
</StoreCtx.Provider>
);
}
將Provider加入todo\src\pages\_app.tsx
import type { AppProps } from "next/app";
import "../style.css";
import "../App.css";
import { StoreProvider } from "../utils/store";
// This default export is required in a new `pages/_app.js` file.
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<StoreProvider>
<Component {...pageProps} />
</StoreProvider>
);
}
到todo\src\pages\index.tsx
加入
function App() {
const { state, dispatch } = useContext(StoreCtx); // Add
const { todos } = state;