react-redux - Redux Reducer 函数有空状态
问题描述
这对我来说有点奇怪,因为我的状态数组在同一个 reducer 的函数中是空的,而在其他的不是。
所以,我的减速器看起来像这样 -
export function booksHasErrored(state = false, action) {
//console.log(action.type);
switch (action.type) {
case 'BOOKS_HAS_ERRORED':
return action.hasErrored;
default:
return state;
}
}
export function booksIsLoading(state = false, action) {
switch (action.type) {
case 'BOOKS_IS_LOADING':
return action.isLoading;
default:
return state;
}
}
export function books(state = [], action) {
switch (action.type) {
case 'BOOKS_FETCH_DATA_SUCCESS':
return action.books;
default:
return state;
}
}
export function updateBook(state = [], action) {
console.log('updateBook');
console.log(state);
console.log(action);
switch (action.type) {
case 'BOOK_UPDATE':
return state;
default:
return state;
}
}
在这个 reducer 中,函数书有一个我所有书的列表的状态。但是,updateBook 函数总是显示空状态数组。在我的 Web 应用程序中,首先调用书籍函数以从 API 调用中获取我所有书籍的列表,然后调用更新函数并且用户导航以更新书籍。我希望我的 updateBook 函数能够接收状态对象及其所有项目。
这就是我组合减速器的方式 -
import {combineReducers} from 'redux';
import {routerReducer} from 'react-router-redux';
import { books, booksHasErrored, booksIsLoading,updateBook } from './books';
import { search, searchHasErrored, searchIsLoading } from './search';
import { authors, authorsHasErrored, authorsIsLoading } from './authors';
//import authors from './authors';
//console.log(books);
const rootReducer = combineReducers({ books,booksHasErrored,booksIsLoading,updateBook,authors,search, searchHasErrored, searchIsLoading, authors, authorsHasErrored, authorsIsLoading,routing:routerReducer});
export default rootReducer;
如果您需要更多信息,请告诉我,我会在此处添加。
解决方案
我可能已经发现了你的问题,你没有返回完整状态,你正在返回动作
export function books(state = [], action) {
switch (action.type) {
case 'BOOKS_FETCH_DATA_SUCCESS':
return action.books;
default:
return state;
}
}
您需要创建一个新状态并对其进行变异,然后将其返回,例如:
export function books(state = [], action) {
switch (action.type) {
case 'BOOKS_FETCH_DATA_SUCCESS':
return state.set('books', action.books);
default:
return state;
}
}
你能改变它,看看它是否有效?
推荐阅读
- docker - 从 dockerhub 提取图像时出现 Kubernetes 错误
- hibernate - Hibernate/JPA - 在保存父实体时将生成的、非 pk/fk 序列生成的列值从父表插入到子表
- c# - 帧窗口与系列的性能问题
- c++ - 来自原始像素数据的 C++ win32 BITMAP 对象
- python - 如何创建嵌套的张量流结构?
- excel - VBA 从函数返回字典
- excel - 当所有参数都指定且非空时,为什么我会收到编译错误 Argument not optional?
- c# - 使用 json.net 反序列化 json 对象数组
- java - JIT C2 方法最大尺寸
- sql-server - 参数超出范围参数名称索引