【问题标题】:What's the Type of value in React Context.Provider under the implementation of React Hooks?React Hooks 实现下 React Context.Provider 中 value 的类型是什么?
【发布时间】:2019-08-12 06:33:53
【问题描述】:

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

但是弹出了一些类型错误,

(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>
)

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

【问题讨论】:

    标签: reactjs typescript react-hooks react-context


    【解决方案1】:

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

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

    但是你试图在其中放置其他东西:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      • 2021-12-12
      • 2020-04-11
      • 1970-01-01
      • 2019-06-30
      • 2019-05-12
      • 1970-01-01
      相关资源
      最近更新 更多