在React Hooks的实现下,React Context.Provider中的值的类型是什么?

时间:2019-08-12 06:33:53

标签: reactjs typescript react-hooks react-context

我做了一段代码来使用useContextuseReducer来实现本地状态管理。

但是弹出一些类型错误,

(property) state: Group
Type '{ state: Group; dispatch: Dispatch<Action>; }' is not assignable to type 'Group'.
  Object literal may only specify known properties, and 'state' does not exist in type 'Group'.ts(2322)
index.d.ts(290, 9): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ProviderProps<Group>'

将类型Group设置为any将解决此问题并正常工作,但我真的不想这样做。

代码如下:

interface People {
  name: string
  age: number
}

interface Group {
  a: People
  b: People
}

interface Action {
  type: string
  payload: number
}

// const myInitalState: Group = {
const myInitalState: any = {
  a: {
    name: 'Max',
    age: 16
  },
  b: {
    name: 'Pom',
    age: 22
  }
}

const myReducer = (state: Group, {type, payload}: Action) => {
  switch (type) {
    case 'a_increase':
      return {...state, a: { ...state.a, age: payload + 1 }}
    case 'b_decrease':
      return {...state, b: { ...state.b, age: payload - 1 }}
    default:
      return state
  }
}

const MyContext = createContext(myInitalState)

const [state, dispatch] = useReducer(myReducer, myInitalState)

const Comp = () => (
  // this state will cause type error, change myInitialState type to any will fix it
  <MyContext.Provider value={{state, dispatch}}>
    <div>Group</div>
           .
           .
           .
  </MyContext.Provider>
)

谁能告诉我这里发生了什么以及如何解决?

1 个答案:

答案 0 :(得分:0)

这是因为您的上下文期望值为Group类型:

const MyContext = createContext(myInitalState); // myInitalState of Group type

但是随后您尝试在其中放置其他内容:

  <MyContext.Provider value={{state, dispatch}}>
  /* here we have
  interface Something {
    state: Group,
    dispatch: Dispatch<Action>
  }
  */