我正在尝试将React Context与Typescript一起使用,并为我的组件创建全局状态管理。
我有这个作为我的州提供者
import React, { createContext, useContext, useReducer } from 'react';
export interface appState {
note: object,
reducer: ({type}:{type: string}) => void;
}
export const StateContext = createContext<appState>({} as appState);
export const StateProvider = (reducer: any, initialState: any, children:any ) => (
<StateContext.Provider value={useReducer(reducer, initialState)}>
{children}
</StateContext.Provider>
);
export const getState = () => useContext(StateContext);
在我的App组件中,我有这段代码
const initialState = {
note: {}
};
interface actionChangeTheme {
type: 'changeTheme',
changeTheme: string
}
const reducer = (state: appState, action: actionChangeTheme) => {
switch (action.type) {
case 'changeTheme':
return {
...state,
theme: action
};
default:
return state;
}
};
return (
<StateProvider initialState={initialState} reducer={reducer}>
...
</StateProvider>
);
我面临的问题是在状态提供程序中,我正在将值分配给value = {useReducer(reducer, initialState)}
,但遇到错误Type '[{}, Dispatch<{}>]' is missing the following properties from type 'appState': note, reducer TS2739
我真的需要有关如何解决此错误的帮助。
Article来自州提供者的想法来自何处
编辑
如果我将界面变成这个
export interface appState {
note?: object,
// reducer: ({type}:{type: string}) => void;
}
我遇到错误,类型为'[{}, Dispatch<{}>]' has no properties in common with type 'appState'.
所以我认为我需要在状态界面上做些事情。