reactjs - React TS useContext useReducer 钩子(Hook)

标签 reactjs typescript 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

有人可以帮我指出我到底做错了什么吗?我是 typescript 新手,所以如果需要请指导我。我试图将状态和分派(dispatch)的上下文值传递给子组件。我不确定发生了什么事。这也是实现 useContext 和 useReducer Hook 的正确方法吗?

最佳答案

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

这是不正确的。

要解决此问题,请将上下文的默认类型设置为 { state,dispatch } (我认为这就是您想要的,将上下文的默认类型设置为 初始状态类型

这是the solution .

关于reactjs - React TS useContext useReducer 钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57298149/

相关文章:

javascript - 在 React 中呈现嵌套/线程评论

reactjs - 使用 AWS Lambda 和 React.js 的无服务器解决方案性能好吗?

reactjs - 将数据从 MongoDB 加载到从我的节点 API 获取的 Redux Store 中

angular - CanLoad 守卫可以在 Electron 应用程序中使用吗?

使用保留名称的 typescript 命名空间声明

typescript - 如何指定 TypeScript 匿名内联箭头函数的返回类型

javascript - react : Getting props from multiple arrays using . map

typescript - 如何使用 fetchApi angular2 TYpescript 在 View 中绑定(bind) Ajax 结果?

c# - 在 Angular 2 和 ASP.NET Core 中使用相对图像路径

f# - 整理我的相互递归类型