商店中的Reducer显示错误(react、redux工具包、typescript)

r6l8ljro  于 2022-11-12  发布在  React
关注(0)|答案(2)|浏览(171)

我在typescript中使用redux,我想创建一个reducer,它将更新store的状态,我的类型是:

interface IArticle {
  id: number,
  title: string,
  body: string,
}

type ArticleState = {
  articles: IArticle[]
}

type ArticleAction = {
  type: string, 
  article: IArticle
}

type DispatchType = (args: ArticleAction) => ArticleAction

我的actionCreators.ts是这样的:

import * as actionTypes from "./actionTypes"

// A function to add an article
export function addArticle(article:IArticle)
{
  const action: ArticleAction={
    type: actionTypes.ADD_ARTICLE,
    article,
  }
  return simulateHttpRequest(action)
}

// A function to remove an article
export function removeArticle(article:IArticle){
  const action: ArticleAction={
    type: actionTypes.REMOVE_ARTICLE,
    article,
  }
  return simulateHttpRequest(action)
}

export function simulateHttpRequest(action: ArticleAction) {
  return (dispatch: DispatchType) => {
    setTimeout(() => {
      dispatch(action)
    }, 500)
  }
}

而我的减速器如下:

import * as actionTypes from "./actionTypes"

const initialState: ArticleState = {
  articles:[]
}
let lastID =0
const reducer = (state:ArticleState=initialState,action:ArticleAction)=>{
  switch(action.type){
    case actionTypes.ADD_ARTICLE:
      const newArticle:IArticle = {
        id: ++lastID,
        title: action.article.title,
        body: action.article.body
      }
      return { ...state,newArticle}

    case actionTypes.REMOVE_ARTICLE:
      return state.articles.filter((article)=> article.id !== action.article.id)
    default: return state
  }
}

export default reducer

到目前为止一切都很好。最后,我的减速器显示一个错误,当我试图使一个商店如下:

export const store = configureStore({
  reducer: {
    reducer: reducer,
  }
});

错误:

Type '(state: ArticleState | undefined, action: ArticleAction) => ArticleState | IArticle[] | { newArticle: IArticle; articles: IArticle[]; }' is not assignable to type 'Reducer<ArticleState | IArticle[] | { newArticle: IArticle; articles: IArticle[]; }, AnyAction>'.
  Types of parameters 'state' and 'state' are incompatible.
    Type 'ArticleState | IArticle[] | { newArticle: IArticle; articles: IArticle[]; } | undefined' is not assignable to type 'ArticleState | undefined'.
      Property 'articles' is missing in type 'IArticle[]' but required in type 'ArticleState'.ts(2322)
type.d.ts(10, 3): 'articles' is declared here.

任何帮助都将不胜感激

y1aodyip

y1aodyip1#

我想它是在抱怨这条线

return { ...state, newArticle}

您正在用一篇文章覆盖文章数组。您应该将新条目添加到现有数组中,并将其合并到状态中。以下是一种方法:

case actionTypes.ADD_ARTICLE:
  const newArticle:IArticle = {
    id: ++lastID,
    title: action.article.title,
    body: action.article.body
  }
  const newItems = [...state.articles, newArticle];
  return { articles: newItems };
xpcnnkqh

xpcnnkqh2#

最后,我找到了解决问题的方法。在reducer函数中,action必须是AnyAction类型

const ArticleReducer = (
  state: ArticleState = initialState ,
  action: ArticleAction | AnyAction
)

相关问题