我是Typescript
的新手,想练习一个名为redux-actions
的库。
https://youtube.com/watch?v=8DH7Ekp2PWI&feature=shares
我尝试使用redux-actions
教程
https://redux-actions.js.org/introduction/tutorial
但是它不能像他们建议的那样在jsfidle或codepen中工作,所以我认为更好的方法是修改YouTube教程,并使用YouTube视频中代码库中的redux-actions
库。
Youtube教程的代码库在github上。
https://github.com/Jon-Peppinck/react-redux-ts
但是,我有麻烦的行动和减速器组件。以下是我已经尝试Counter.ts
export interface Counter {
count: number;
}
CounterActions.ts
import { createActions } from "redux-actions";
export const { increment, decrement } = createActions({
INCREMENT: (amount = 1) => ({ amount }),
DECREMENT: (amount = 1) => ({ amount: -amount }),
});
interface IncrementAction {
type: typeof increment;
}
interface DecrementAction {
type: typeof decrement;
}
export type CounterActionTypes = IncrementAction | DecrementAction;
CounterReducer.ts
import { handleActions } from "redux-actions";
import { CounterActionTypes, decrement, increment } from "./CounterAction";
import { Counter } from "./models/Counter";
const defaultState: Counter = {
count: 0,
};
export const counterReducer = handleActions(
{
[increment]: (state: Counter, { payload: { amount } }: any): Counter => {
return { ...state, count: state.count + amount };
},
[decrement]: (state: Counter, { payload: { amount } }: any): Counter => {
return { ...state, count: state.count + amount };
},
},
defaultState
);
但递增和递减操作显示错误:
计算属性名必须是“string”、“number”、“symbol”或“any”类型。ts(2464)
我也不确定我用any
输入payload
的方式,有没有更好的方式来输入它。我如何修复我的代码并防止错误?还有,有没有关于使用redux操作的资源或教程不是付费内容。我搜索了一下,但我找不到任何东西。
2条答案
按热度按时间yuvru6vn1#
我是还原版的维护者。
请 * 不要 * 使用
redux-actions
!它已经过时了,使用它需要编写大量您不需要编写的代码。
相反,今天您应该使用我们的官方Redux工具包。RTK旨在简化和标准化Redux使用模式,并与TypeScript配合使用。
以下是使用RTK时的示例(以及额外的大小写缩减器):
有关如何以及为什么使用Redux Toolkit的详细信息,请参阅我们的文档:
9rbhqvlz2#
看起来问题出在
[increment]
上,我不明白为什么文档中是这样的,但是嘿,它已经4年了。但对我有效的是:
CounterActions.ts
CounterReducer.ts