首页 > 解决方案 > 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;

如果您需要更多信息,请告诉我,我会在此处添加。

标签: react-reduxredux-thunk

解决方案


我可能已经发现了你的问题,你没有返回完整状态,你正在返回动作

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;
    }
}

你能改变它,看看它是否有效?


推荐阅读