gpt4 book ai didi

typescript - 无法在 TypeScript + Redux 中使用 reducer 创建商店

转载 作者:搜寻专家 更新时间:2023-10-30 22:01:00 25 4
gpt4 key购买 nike

我在使用 redux 和 typescript 创建商店时遇到了麻烦。这是 actions.js:

import { Action } from 'redux';

export interface ITodoAction extends Action {
todo:string;
}

export const ADD_TODO:string = 'ADD_TODO';
export function addTodo(todo:string):ITodoAction {
return {
type: ADD_TODO,
todo
};
}

我为名为 ITodoAction 的自定义操作导出了接口(interface),为我的自定义属性 todo:string 扩展了操作。

这是 reducers.js:

import { Reducer } from 'redux';
import { ITodo } from '../interfaces';
import { ITodoAction, ADD_TODO } from '../actions';

let id:number = 0;
const generateId = ():number => id++;

interface ITodoState {
todos:Array<ITodo>
};

const defaultState:ITodoState = {
todos: []
};

export function todoReducer(state:ITodoState = defaultState, action:ITodoAction):ITodoState {
switch(action.type) {
case ADD_TODO:
return Object.assign({}, state, {
todos: [
{ id: generateId(), text: action.todo, completed: false },
...state.todos
]
});
default:
return state;
}
}

我在定义 todoReducer 时使用了之前 actions.js 中的 ITodoAction。 todoReducer 将返回 ITodoState 实例,如下所示:

{
type: 'ADD_TODO',
todos: [ ITodo{}, ITodo{}, ITodo{}, ... ]
}

这是我使用的 ITodo 接口(interface):

export interface ITodo {
id:number;
todo:string;
completed:boolean;
}

它只是包含 id、文本、已完成的普通对象。我认为这看起来不错,但是当我尝试像这样使用 reducer 创建商店时:

import { createStore } from 'redux';
import todoReducer from './reducers';

export const store = createStore(todoReducer);

它失败了:

Argument of type 'typeof "/.../typescript-todo/src/ts/reducers/index"' is not assignable to parameter of type 'Reducer<{}>'...
Type 'typeof "/./typescript-todo/src/ts/reducers/index"' provides no match for the signature '&lt;A extends Action&gt;(state: {}, action: A): {}'

看起来我必须修复我的 reducer,但我不知道如何使用 Reducer<{}> 定义 reducer,我每次尝试都失败并显示类似的消息,例如“blablabla 不可分配给 blablabla”。

我想要的只是使用我的简单 reducer ,但为什么我不能?它也不会与 combineReducer 一起工作,此时,它需要使用某种 ReducerMap 或其他东西,我不记得实际接口(interface)是什么。

我发现了很多 typescript + redux 相关的帖子,但他们没有使用 Reducer<{}> 或 Action>T< 之类的东西,他们只是使用了他们自己定义的 Action 和 Reducer,但这些让我困惑,为什么他们不使用 Reducer 和 Action 接口(interface),为什么它起作用了?

不知何故,我找到了 redux 的类型声明,这就是 Reducer<{}> 的样子:

export type Reducer<S> = <A extends Action>(state: S, action: A) => S;

据我所知,Reducer<{}> 是一个返回状态的函数。那为什么我的 todoReducer 不能和他们一起工作呢?我尝试使用 Reducer ,但它不起作用。

我现在真的很困惑,看起来我错过了一些重要的东西,但是,哇,我真的不明白我错过了什么。我从没想过将 Redux 与 TypeScript 结合使用会很困难。

我尽力了,但看起来我需要帮助。任何建议将不胜感激。

最佳答案

已修复,只需将 reducer 导出为默认值,即可正常工作。

关于typescript - 无法在 TypeScript + Redux 中使用 reducer 创建商店,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41768182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com