类型'TodosState'不是数组类型.ts(2461)

时间:2019-03-28 16:44:29

标签: reactjs typescript redux

我第一次尝试在项目中使用TypeScript,但我一直坚持在操作和化简器之间正确设置类型

这里是类型

types.ts

// Todo Type
export interface Todo {
  _id: string,
  content: string,
  completed?: boolean,
}

export interface TodosState {
  todos: Todo[]
}

// Read

export const TODOS_READ_KEY = 'TODOS_READ_KEY'
export const TODOS_READ_REQUEST_KEY = 'TODOS_READ_REQUEST_KEY'
interface TodosReadAction {
  type: typeof TODOS_READ_KEY
  payload: TodosState
}



// Add
export const TODO_ADD_KEY = 'TODO_ADD_KEY'
export const TODOS_ADD_REQUEST_KEY = 'TODOS_ADD_REQUEST_KEY'

interface AddTodoAction {
  type: typeof TODO_ADD_KEY
  payload: Todo
}




export type TodoActionTypes =  AddTodoAction | TodosReadAction

...以及动作

actions.ts

import {
  Todo,
  TODO_ADD_KEY,
  TODOS_READ_REQUEST_KEY,
  TODOS_READ_KEY,
  TODOS_ADD_REQUEST_KEY
} from './types'
import { createRequestThunk } from '../action-helpers'
import { ICreateRequestThunk } from '../action-helpers-types'
import api from '../../api'
// import { red } from '../../logger'
import { orange } from '../../logger'

export function todoAdd(newTodo: Todo) {
  orange('todoAdd: todo', newTodo);

  return {
    type: TODO_ADD_KEY,
    payload: newTodo,
  }
}

export const todosRead = (todos: Todo[]) => {
  return ({
    type: TODOS_READ_KEY,
    payload: todos,
  })
}

// Read
const todoReadRequestCall: ICreateRequestThunk = {
  request: api.todos.read,
  key: TODOS_READ_REQUEST_KEY,
  success: [todosRead],
  failure: [(error) => console.log('(7) todoReadRequestCall: request failed', error)]
}

// Post
const todoAddRequestCall: ICreateRequestThunk = {
  request: api.todos.create,
  key: TODOS_ADD_REQUEST_KEY,
  success: [todoAdd],
  failure: [(error) => console.log('(7) todoAddRequestCall: request failed', error)]
}

export const todoAddRequest = createRequestThunk(todoAddRequestCall)

问题出现在以下reducers.ts中。todos: [...state, action.payload]行中的“状态”带有红色下划线,并且错误提示

Type 'TodosState' is not an array type.ts(2461)

如果我将其更改为

todos: [...state.todos, action.payload]

红色下划线消失了,但随后出现运行时错误

TypeError: "state.todos is undefined"
    Redux 2
    y (index):1
    h (index):1
    b (index):1
    dispatch Redux
    e (index):1
    Redux 4
        createThunkMiddleware
        dispatch
        createRequestThunk
        createRequestThunk

reducers.ts

import {
  TodosState,
  TODO_ADD_KEY,
  TodoActionTypes,
  TODOS_READ_KEY
} from './types'

const initialState: TodosState = {
  todos: []
}

export function todosReducer(
  state = initialState,
  action: TodoActionTypes
): TodosState {

  switch (action.type) {
    case TODOS_READ_KEY:
      return action.payload
    case TODO_ADD_KEY:
      return {
        todos: [...state, action.payload]
      }
    default:
      return state
  }
}

1 个答案:

答案 0 :(得分:0)

也许可以在减速器中尝试一下

return {
  ...state,
  todos: [...state.todos, action.payload]
}