ค้นหาเว็บไซต์

javascript - useContext และ useReducer ใน typescript


ผมเป็นมือใหม่ใน typescript และกำลังใช้งาน react useContext และ useReducer ผมกำลังทำตามบทเรียนแต่ได้รับข้อผิดพลาด Parameter 'action' implicitly has an 'any' type. ในฟังก์ชัน reducer ของผม

ฟังก์ชันรีดิวเซอร์

function reducer(state, action) { // error Parameter 'action' implicitly has an 'any' type.
     return { count: state.count + 1 }
}

ผู้ให้บริการนับ

   const [state, dispatch] = useReducer(reducer, {
    count: 0
   })

คำตอบ #1

คุณต้องระบุประเภทของการกระทำเป็นใดก็ได้หรือทำมันโดยรูปแบบทั่วไป ในกรณีที่คุณต้องการจัดโครงสร้างการกระทำ คุณสามารถสร้างอินเทอร์เฟซได้

function reducer(state, action: { [key: string]: string|number }) { // error Parameter 'action' implicitly has an 'any' type.
    return { count: state.count + 1 }
}

คำตอบ #2

ก่อนอื่นคุณต้องพิมพ์ผู้สร้างแอ็กชันของคุณอย่างถูกต้อง:

Actions.ts

export const increment = (
  background: string
): {
  type: "INCREMENT";
  payload: {
    background: string;
  };
} => ({
  type: "INCREMENT",
  payload: {
    background
  }
});

export const decrement = (
  background: string
): {
  type: "DECREMENT";
  payload: {
    background: string;
  };
} => ({
  type: "DECREMENT",
  payload: {
    background
  }
});

export type Action =
  | ReturnType<typeof increment>
  | ReturnType<typeof increment>;

จากนั้นในรีดิวเซอร์ของคุณคุณควรนำเข้าประเภทของแอคชันของคุณ:

Reducer.ts

import type { Action } from "./actions";

export const initialState = {
  count: 0
};

export type Store = typeof initialState;

export const reducer = (state: Store, action: Action) => {
  switch (action.type) {
    case "INCREMENT":
      return { count: state.count + 1 };
    default:
      return state;
  }
};

และสุดท้ายสำหรับการพิมพ์ useReducer hook ของคุณที่ใดก็ได้ในแอปของคุณ:

ผู้ให้บริการนับ

import type { Store } from "./context/reducer";
import type { Action } from "./context/actions";

const [state, dispatch] = useReducer<React.Reducer<Store, Action>>(
    reducer,
    initialState
  );

คุณสามารถอ่านเพิ่มเติมเกี่ยวกับเรื่องนี้ได้ที่นี่: การพิมพ์ useReducer และ Context API ของ React อย่างมีสไตล์ด้วย discriminated union ของ Typescript