【问题标题】:TypeScript - How to splite react context with dispatch actions?TypeScript - 如何将反应上下文与调度动作分开?
【发布时间】:2021-04-18 00:14:17
【问题描述】:

我目前正在尝试使用 createContextuseReducer 构建简单的待办事项应用程序,但我目前被 TypeScript 部分困住,无法弄清楚如何解决此问题

Argument of type '(state: todos[], action: action) => todos[]' is not assignable to parameter of type 'action'.
  Type '(state: todos[], action: action) => todos[]' is missing the following properties from type '{ type: "delet"; id: string; }': type, id  TS2345

     9 | 
    10 | export const AppContext = createContext<todos[]>([]);
  > 11 | export const AppReducerContext = createContext<action>(Reducer);
       |                                                        ^
    12 | 
    13 | const initData: todos[] = [];
    14 |

上下文文件:

import React, { createContext, useReducer } from "react";
import Reducer, { action } from "./Reducer";

export interface todos {
  id: string;
  task: string;
  completed: boolean;
}

export const AppContext = createContext<todos[]>([]);
export const AppReducerContext = createContext<action>(Reducer);

const initData: todos[] = [];

export const AppContextProvider: React.FC = ({ children }) => {
  const [state, dispatch] = useReducer(Reducer, initData);

  return (
    <AppContext.Provider value={state}>
      <AppReducerContext.Provider value={dispatch}>
        {children}
      </AppReducerContext.Provider>
    </AppContext.Provider>
  );
};

reducer 文件

import { todos } from "./Context";
import { v4 as uuid } from "uuid";

export type action =
  | { type: "add"; task: string }
  | { type: "delet"; id: string };

const Reducer = (state: todos[], action: action) => {
  switch (action.type) {
    case "add":
      return [...state, { id: uuid(), task: action.task, completed: false }];
    case "delet":
      return state.filter((todo) => todo.id !== action.id);
    default:
      return state;
  }
};

export default Reducer;

那么我如何使用createContext()dispatch 操作配置调度

这是我试图转换为打字稿的参考代码:- https://github.com/Colt/todos-context-usereducer/blob/4-split-contexts/src/context/todos.context.js

【问题讨论】:

    标签: javascript reactjs typescript react-context


    【解决方案1】:

    nvm 我想通了

    export const AppReducerContext = createContext<React.Dispatch<action>>(
      () => {}
    );
    

    如果你想拆分上下文就用这个

    【讨论】:

      猜你喜欢
      • 2021-01-16
      • 2022-11-02
      • 2019-07-17
      • 2020-01-21
      • 2019-12-24
      • 2019-06-10
      • 2019-06-14
      • 1970-01-01
      • 2022-06-10
      相关资源
      最近更新 更多