【发布时间】: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