2 回答
TA贡献1783条经验 获得超4个赞
createContext参数类型应与您的值ContextOne.Provider类型匹配。您还需要改进您的类型以指导更多的TypeScript编译器:
import * as React from "react";
type State = {
count: number
currentColor: string
}
const initialState: State = {
count: 10,
currentColor: "#bada55",
};
type Context = {
state: State
dispatch: React.Dispatch<State>
}
const ContextOne = React.createContext<Context>({
state: initialState,
dispatch: () => {},
});
// You need to define the type Action
const reducer: React.Reducer<State, Action> = (state, action) => {
switch (action.type) {
case "reset":
return initialState;
case "increment":
return { ...state, count: state.count + 1 };
case "decrement":
return { ...state, count: state.count - 1 };
case "set-color":
return { ...state, currentColor: action.payload };
}
};
function ContextOneProvider(props) {
const [state, dispatch] = React.useReducer(reducer, initialState);
const value: Context = { state, dispatch };
return (
<ContextOne.Provider value={value}>{props.children} </ContextOne.Provider>
);
}
let ContextOneConsumer = ContextOne.Consumer;
export { ContextOne, ContextOneProvider, ContextOneConsumer };
TA贡献1966条经验 获得超4个赞
您的问题是您正在向具有属性的上下文提供者提供初始状态countand currentColor,而您提供的值(新状态)ContextOneProvider具有属性stateand dispatch。
我想您会希望将 initialState 交换为以下内容:
{
state: null,
dispatch: null,
}
如果您使用的是打字稿,您可能希望提供一个将这些作为可选参数的接口。
添加回答
举报