我做了一段代码来使用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>
)
谁能告诉我这里发生了什么以及如何解决?
答案 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>
}
*/