将 redux 状态传递给 reducer

Passing redux state to reducer

我正在尝试通过单击从 dom 中删除一个元素。我在没有 redux thunk 的情况下没有问题,但现在我遇到了问题。我的减速器不知道状态。怎么让他知道是什么物品?

操作:

export function deleteItem(index) {
    return {
        type: 'DELETE_ITEM',
        index
    };
}

我的减速器显示未定义。

export function deleteItem(state = [], action) {
    switch (action.type) {
        case 'DELETE_ITEM':
            const copy = state.items.slice()
            console.log(copy)
        default:
            return state;
    }
}

这是我的实际代码https://github.com/KamilStaszewski/flashcards/tree/develop/src

默认表示reducer的初始状态,状态是一个空数组,你不能访问state.items,因为它是未定义的。假设这样:

const x = [];
x.foo.slice();

那会 return 出错。因此来自:

state = []

将其更改为:

state = {
     items:[]
}

将它应用到您的代码中:

export function deleteItem(   
state = {
     items:[]
}, 
action) {
    switch (action.type) {
        case 'DELETE_ITEM':
            const copy = state.items.slice()
            console.log(copy)
        default:
            return state;
    }
}

我看到了你的代码,你正在为你想要对你的项目完成的每个操作定义一个新的减速器(e.i itemsHaveError,deleteItem,...)但是这样做的正确方法是将项目的所有相关功能存储到单个 reducer 中,该 reducer 保存每当对项目进行某些操作时需要更改的数据,但是以您的方式,任何时候任何操作都会发生,因为您的 reducer 与初始分离state 变空,因为你已经传递给函数,reducer 不知道它们的相关数据,所以它们用空的初始状态覆盖它们,正确的方法是这样为项目编写一个 reducer:

    const initialState = {
      isLoading: false,
      hasError: false,
      items: [],
    };

    export default function(state = initialState, action) {
      switch (action.type) {
        case ITEMS_HAVE_ERROR:
          return {
            ...state,
            hasError: action.hasError,
          };
        case ITEMS_ARE_LOADING:
          return {
            ...state,
            isLoading: action.isLoading,
          };
        case ITEMS_FETCH_DATA_SUCCESS:
          return {
            ...state,
            items: action.items,
          };
        case DELETE_ITEM:
          const copy = state.items.slice()
          return {
            ...state,
            items: copy,
          };      
        default:
          return state;
      }
    }

所以这将是您的 item.js 和您的 item reducer,并且是唯一一个应该使用 combineReducer 函数的。