我遇到有关
的问题在每个“类型'数字'不能分配给类型'从不'。'
'类型'数字'不能分配给类型'从不'。'
'类型'string'不能分配给类型'never'。'
“'数字'类型不能分配给'从不'类型。”
id
,col
,color
,height
上。 ColsContextProvider
中有4次。
我认为这可能是Colstate[]
的问题,但我找不到解决方法。
import React, { createContext, Dispatch, useReducer, useContext } from "react";
export const ADD_SQUARE = "ADD_SQUARE" as const;
export const CHANGE_SQUARE = "CHANGE_SQUARE" as const;
export const DELETE_SQUARE = "DELETE_SQUARE" as const;
export type Square = {
id: number;
col: number;
color: string;
height: number;
};
type ColState = Square[];
const ColsStateContext = createContext<ColState[] | void>(undefined);
type Action =
| {
type: "ADD_SQUARE";
id: number;
col: number;
color: string;
height: number;
}
| { type: "CHANGE_SQUARE"; id: number; col: number; color: string }
| { type: "DELETE_SQUARE"; id: number; col: number };
type ColsDispatch = Dispatch<Action>;
const ColsDispatchContext = createContext<ColsDispatch | undefined>(undefined);
function colsReducer(state: ColState[], action: Action) {
switch (action.type) {
case ADD_SQUARE:
return console.log("DELETE_SQUARE");
case CHANGE_SQUARE:
return console.log("CHANGE_SQUARE");
case DELETE_SQUARE:
return console.log("DELETE_SQUARE");
default:
return state;
}
}
export function ColsContextProvider({
children
}: {
children: React.ReactNode;
}) {
const [cols, dispatch] = useReducer(colsReducer, [
[
{
id: 1,
col: 1,
color: "#111",
height: 80
},
{
id: 2,
col: 1,
color: "#aca",
height: 110
}
],
[
{
id: 1,
col: 2,
color: "#cbb",
height: 35
}
],
[
{
id: 1,
col: 3,
color: "#aac",
height: 20
}
]
]);
return (
<ColsDispatchContext.Provider value={dispatch}>
<ColsStateContext.Provider value={cols}>
{children}
</ColsStateContext.Provider>
</ColsDispatchContext.Provider>
);
}
export function useColsState() {
const state = useContext(ColsStateContext);
if (!state) throw new Error("Cols provider problem");
return state;
}
export function useColsDispatch() {
const dispatch = useContext(ColsDispatchContext);
if (!dispatch) throw new Error("Cols provider problem");
return dispatch;
}
答案 0 :(得分:1)
您需要在colsReducer
中返回正确的状态。
您将在console.log()
函数中返回colsReducer
。这使得返回类型colsReducer
void | Square[][]
无法推断,因此useReducer
中第二个参数的类型变为never
。
按如下所示编辑代码,然后查看要执行的操作。
function colsReducer(state: ColState[], action: Action) {
// ...
}
更改为:
function colsReducer(state: ColState[], action: Action): ColState[] {
// ...
}