reactjs - ฉันจะแก้ไขข้อผิดพลาดประเภท "argument ไม่สามารถมอบหมายให้กับพารามิเตอร์ประเภท never" สำหรับ useReducer hook ได้อย่างไร?
การเลื่อนเมาส์ไปเหนือตัวแปร todos ในฟังก์ชัน useReducer ของฉันที่นี่: const [state, dispatch]=useReducer(reducer, todos); จะทำให้เกิดข้อผิดพลาดประเภทดังต่อไปนี้
Argument of type 'TodoState[]' is not assignable to parameter of type 'never'.
ฉันได้ลองเพิ่ม TodoState[] เป็นประเภทผลลัพธ์ในฟังก์ชัน reducer ของฉันเพื่อให้แน่ใจว่าฉันไม่ได้เผลอคืนค่า never[] อย่างไรก็ตาม ข้อผิดพลาดยังคงมีอยู่:
โค้ดที่เกี่ยวข้องมีดังนี้:
interface TodoState {
id: string;
}
interface TodoAction {
type?: 'CREATED' | 'DELETED' | 'UPDATED';
payload?: TodoState;
}
interface TodoReducer {
state: TodoState[];
action: TodoAction;
}
interface TodosProviderProps {
children: ReactChildren;
todos: TodoState[];
}
const reducer = ({ state = [], action = {} }: TodoReducer): TodoState[] => {
const { payload, type } = action;
const mutatedItem = payload;
if (!mutatedItem) {
return state;
}
const mutatedIndex = state.findIndex((item) => item.id === mutatedItem.id);
switch (type) {
case 'CREATED':
if (mutatedIndex < 0) {
state.push(mutatedItem);
}
break;
case 'DELETED':
if (mutatedIndex >= 0) {
state.splice(mutatedIndex, 1);
}
break;
case 'UPDATED':
state[mutatedIndex] = mutatedItem;
break;
default:
return state;
}
return state;
};
export function TodosProvider({ children, todos }: TodosProviderProps) {
const [state, dispatch] = useReducer(reducer, todos);// type error for todos here
// rest of code
}
คำตอบ #1
หลังจากตรวจสอบเอกสารแล้ว ฉันพบว่า ฟังก์ชัน reducer จะรับพารามิเตอร์สองตัว แทนที่จะเป็นอ็อบเจ็กต์ที่คุณได้ทำการแยกโครงสร้างแล้ว
ดังนั้น บรรทัดควรเป็น:
const reducer = (state:TodoState[] = [], action:TodoAction = {}): TodoState[] => {