ReactJS - تایپ کردن useReducer به عنوان یک مقدار کانتکست
من میخواهم useReducer را به عنوان یک مقدار در StateContext.Provider منتقل کنم. هنگام تلاش برای استفاده از useReducer با استفاده از useContext(StateContext)، خطای زیر را دریافت میکنم:
نوع '[initialStateType, Dispatch] | null' یک نوع آرایه نیست
من یک راهحل موقت پیدا کردم:
export const StateContext = createContext([] as unknown as [initialStateType, Dispatch<Action>]);با این حال، مطمئن نیستم که این اظهارنظر نوع بهترین روش باشد. بهترین راه برای نوعدهی useReducer به عنوان یک مقدار کانتکست چیست؟
در اینجا کد مربوطه آمده است:
stateProvider.tsx
export const StateContext = createContext< [initialStateType, Dispatch<Action>] | null>(null);
export const StateProvider = ({ reducer, initialState, children }: StateProviderProps) => {
return (
<StateContext.Provider value={useReducer(reducer, initialState)}>
{children}
</StateContext.Provider>
)
}
Product.tsx
export const Product = ({id,title,image,price, rating}: ProductProps) => {
const [state,dispatch] = useContext(StateContext); // error: Type '[initialStateType, Dispatch<Action>] | null' is not an array type.
}
پاسخ شماره ۱
یک interface تعریف کنید که وضعیت را مشخص کند و یک شیء که مقدار اولیه آن را در بر دارد:
interface AppState {
}
const initialState: AppState = {
}
export const StateContext = createContext<AppState>(initialState);
export const StateProvider = ({
reducer,
initialState,
children,
}: StateProviderProps) => {
const [state, dispatch] = useReducer(reducer, initialState);
// Define helper methods that will `dispatch` the various events
return (
<StateContext.Provider value={{
...state
}}>
{children}
</StateContext.Provider>
);
};
