React TS useContext useReducer钩子

时间:2019-07-31 20:08:08

标签: reactjs types react-hooks

我无法弄清楚这段代码中的类型错误

import React from 'react';

interface IMenu {
  items: {
    title: string,
    active: boolean,
    label: string
  }[]
}


type Action =
  | { type: 'SET_ACTIVE', label: string }

const initialState: IMenu = {
  items: [
    { title: 'Home', active: false, label: 'home' },
    { title: 'Customer', active: false, label: 'customer' },
    { title: 'Employee', active: false, label: 'employee' },
    { title: 'Report', active: false, label: 'report' },
  ]
}

const reducer = (state: IMenu = initialState, action: Action) => {
  switch (action.type) {
    case 'SET_ACTIVE': {
      const label = action.label;
      const items = state.items.map((item) => {
        if (item.label === label) {
          return { ...item, active: true };
        }
        return { ...item, active: false }
      })
      return { items }
    }
    default:
      throw new Error();
  }
};

export const MenuContext = React.createContext(initialState);
export const MenuConsumer = MenuContext.Consumer;

export function MenuProvider(props: any) {
  const [state, dispatch] = React.useReducer(reducer, initialState)
  const value = { state, dispatch };
  console.log(value)
  return (
    <MenuContext.Provider value={value}>
      {props.children}
    </MenuContext.Provider>
  )
}

我收到的错误是这个

    /Volumes/Tarang External/react-context-typescript/src/context/index.tsx
TypeScript error in /Volumes/Tarang External/react-context-typescript/src/context/index.tsx(49,27):
Property 'items' is missing in type '{ state: { items: { active: boolean; title: string; label: string; }[]; }; dispatch: Dispatch<{ type: "SET_ACTIVE"; label: string; }>; }' but required in type 'IMenu'.  TS2741

    47 |   console.log(value)
    48 |   return (
  > 49 |     <MenuContext.Provider value={value}>
       |                           ^
    50 |       {props.children}
    51 |     </MenuContext.Prov

有人可以指出我到底在做什么错吗?我是打字稿新手,因此如有必要请指导我。我试图传递状态的上下文值并将其分派给子组件。我不确定会发生什么。这也是实现useContext和useReducer挂钩的正确方法吗?

2 个答案:

答案 0 :(得分:1)

更新:

您可以这样定义上下文类型:

type StoreApi = {
  state: typeof initialState
  dispatch: React.Dispatch<Action>
}

然后定义MenuContext,例如像这样:

// undefined is just the default in case, you don't have a provider defined
export const MenuContext = React.createContext<StoreApi | undefined>(undefined)
// or if you want it more like your first example
export const MenuContext = React.createContext<StoreApi | typeof initialState>(initialState)

答案 1 :(得分:0)

您的问题是您的上下文应该与initialState具有相同的类型,但是您将上下文的默认值设置为{ state, dispatch }

这是不正确的。

要解决此问题,可以将上下文的默认类型设置为{ state, dispatch }(我想这就是您想要的,或者将上下文的默认类型设置为typeof initialState

这里是the solution