【发布时间】: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