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,
}
如果您使用的是打字稿,您可能希望提供一個將這些作為可選參數的接口。
添加回答
舉報