【问题标题】:Setting up React / Redux typescript for hooks为钩子设置 React / Redux 打字稿
【发布时间】:2020-08-27 20:53:30
【问题描述】:

我一直在网上寻找不同的资源,试图为我所拥有的东西找到一个可行的解决方案,到目前为止,我认为我的打字稿集成有点糟糕。我很想在正确设置我的钩子类型方面得到一些帮助。

我有一个useUser() 钩子,它可以将操作分派到我的reducer 并从我的商店返回选择器。我已经取得了一些进展,但我开始有点不知所措了。

钩子:useUser.ts

  • 我不确定我可以放置什么作为这个钩子的返回值。我尝试放置useUserActionTypes,但我认为这没有任何区别,特别是因为除了获取对象(userData)或数字之外,我没有返回任何东西 (totalPoints, totalWords) 来自商店。
  • 我认为我不应该“退回”我的调度,但它让 typescript 不那么沮丧
  • 例如,我也可以在我的调度类型中输入类似“Dog”而不是FETCH_USER 的内容。可能没关系,但我认为里面应该有保障,对吧?
  • 非常困惑如何在解构返回中实际修复该错误。我有一个名为 User 的类型,它代表我的商店将为用户提供的对象,但是......这没有什么区别。
import { useSelector, useDispatch } from 'react-redux';
import axios from 'axios';
import { User } from '../reducers/user';

export const FETCH_USER = 'FETCH_USER';
export const UPDATE_ERRORS = 'UPDATE_ERRORS';
export const INCREMENT_POINTS = 'INCREMENT_POINTS';
export const INCREMENT_WORDS = 'INCREMENT_WORDS';

type Error = {
  code: number;
  message: string;
};

type FetchUserAction = {
  type: typeof FETCH_USER;
  payload: User;
};

type UpdateErrorsAction = {
  type: typeof UPDATE_ERRORS;
  payload: Error[];
};

type IncrementPointsAction = {
  type: typeof INCREMENT_POINTS;
  payload: number;
};

type IncrementWordsActions = {
  type: typeof INCREMENT_WORDS;
};

// ? Typescript is able to infer the correct type in the Union Type below
export type useUserActionTypes =
  | FetchUserAction
  | UpdateErrorsAction
  | IncrementPointsAction
  | IncrementWordsActions;

export type ReduxStore = {
  alert: any;
  user: User;
};

const useUser = (): useUserActionTypes => {
  const userData: User = useSelector((state: ReduxStore) => state.user);
  const totalPoints: number = useSelector(
    (state: ReduxStore) => state.user.points
  );
  const totalWords: number = useSelector(
    (state: ReduxStore) => state.user.words
  );
  const dispatch = useDispatch();
  const fetchUser = async (): Promise<FetchUserAction | UpdateErrorsAction> => {
    try {
      const response = await axios.get(
        'http://localhost:5000/api/v1/users/WhpHq4qWFdzlhlx2ztqD'
      );
      const user = response.data;
      return dispatch({
        type: FETCH_USER,
        payload: user,
      });
    } catch (error) {
      return dispatch({
        type: UPDATE_ERRORS,
        payload: [
          {
            code: 500,
            message: error.message,
          },
        ],
      });
    }
  };
  const incrementPoints = (amount: number): useUserActionTypes => {
    return dispatch({
      type: INCREMENT_POINTS,
      payload: amount,
    });
  };
  const incrementWords = (): useUserActionTypes => {
    return dispatch({
      type: INCREMENT_WORDS,
    });
  };
  return {
    userData,
    totalPoints,
    totalWords,
    fetchUser,
    incrementPoints,
    incrementWords,
  };
};

export default useUser;


在我尝试使用选择器的页面上:

  • 我认为这些都包含在我的钩子中,我为这些常量分配了类型。
  • fetchUser() 返回一种“任何”类型...可能与上述相同的问题?

感谢您的帮助,尝试将这一切与打字稿正确连接绝对很有趣,但我目前有点迷茫。

【问题讨论】:

  • useUserActionTypes 类型对于 useUser 返回的类型是错误的,useUser 被键入以返回单个操作(具有类型和有效负载键的对象),而它实际上返回多个事物,而 fetchUser 是操作创建者而不是操作。

标签: javascript reactjs typescript redux react-hooks


【解决方案1】:

问题是您输入了错误的useUser,根据您的代码,正确的返回类型是:

{
    userData: User;
    totalPoints: number;
    totalWords: number;
    fetchUser(): Promise<FetchUserAction | UpdateErrorsAction>;
    incrementPoints(amount: number): useUserActionTypes;
    incrementWords(): useUserActionTypes;
}

Playground

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 2019-10-28
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 2020-07-11
    • 2018-10-04
    • 1970-01-01
    相关资源
    最近更新 更多