了解redux中的减速器和组合减速器



所以我使用redux,并编写了一个reducer来管理todos;

import { combineReducers } from "redux";
import { ADD_TODO, COMPELETE_TODO, REMOVE_TODO } from "./actiontypes";
const initialState = {
todos: [],
};
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TODO:
return {
...state,
todos: [...state.todos, action.payload],
};
case COMPELETE_TODO:
case REMOVE_TODO:
return {
...state,
todos: state.todos.filter(
(todo) => state.todos.indexOf(todo) != action.payload
),
};
default:
return state;
}
};
export default combineReducers({
rootReducer,
});

正如您所看到的,我创建了一个reducer和用户combineReducer,然后将其传递到其他文件中存储,它运行良好。

现在我对combineReducer的理解是,当我们单独编写它们时,它将单独的缩减器组合在一起。所以,如果我把上面的减速器(因为我只有一个减速器(改为以下;

import { ADD_TODO, COMPELETE_TODO, REMOVE_TODO } from "./actiontypes";
const initialState = {
todos: [],
};
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TODO:
return {
...state,
todos: [...state.todos, action.payload],
};
case COMPELETE_TODO:
case REMOVE_TODO:
return {
...state,
todos: state.todos.filter(
(todo) => state.todos.indexOf(todo) != action.payload
),
};
default:
return state;
}
};
export default rootReducer;

并将其传递给状态,但它会出错。当我尝试使用useSelector访问todos时,它给出了未定义;

const {todos} = useSelector(state => ({
todos: state.rootReducer.todos
}))

所以我认为我没有正确理解combineReducers。请解释造成上述错误的原因。

Combine reducer根据传入对象的键,将名称空间添加到每个reducer控制的状态中。如果不使用Combine reductor,就不会有名称空间。因此,将state.rootReducer更改为state。

combineReducers创建一个将组合减速器的状态分离的减速器。在文档中,他们展示了这个例子:

rootReducer = combineReducers({potato: potatoReducer, tomato: tomatoReducer})

这将产生以下状态对象

{
potato: {
// ... potatoes, and other state managed by the potatoReducer ...
},
tomato: {
// ... tomatoes, and other state managed by the tomatoReducer, maybe some nice sauce? ...
}
}

因此,当你写时

combineReducers({
rootReducer,
});

状态对象将是

{
rootReducer: {
// rootReducer's state
}
}

在第二个示例中,您只返回rootReducer。因此,没有单独的州。rootReducer在根状态下运行。因此,您必须调整选择。

const {todos} = useSelector(state => ({
todos: state.todos
}))

相关内容

  • 没有找到相关文章

最新更新