首页 > 解决方案 > React & Redux - TypeError 状态不可迭代

问题描述

我想将对象添加到我的 Redux 中存在的数组中。如果我不添加 redux-persist,代码可以正常工作,但是在添加 redux-persist 之后,我得到一个 TypeError,即 state is not Iterateable。我想用 redux-persist 运行代码。有什么办法吗?

添加 redux-persist 之前的我的商店代码:

import rootReducer from './reducer';
import {createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';

const store = createStore(
    rootReducer,
    {},
    applyMiddleware(thunk)
);

export default store;

Reducer.js 代码如下:

const INITIAL_STATE = {
    reduxArray : []
}

export default (state = INITIAL_STATE, action) => {
    switch (action.type) {

        case 'POPULATEARRAY':
            return ({
                 ...state,
                reduxArray : [action.payload , ...state.reduxArray]
            })

        default:
            return state;
    }

}

Action.js 代码如下:

export function Populate(data) {
    return dispatch => {
        dispatch({ type: 'POPULATEARRAY', payload: data  })
    }
}

添加 redux-persist 后我的商店代码:

import rootReducer from './reducer';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

const persistConfig = {
    key: 'root',
    storage,
}


const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = createStore(persistedReducer, applyMiddleware(thunk));
const persistor = persistStore(store);
export { store, persistor };

标签: javascriptreactjsredux

解决方案


你的函数 insReducer.js不正确。该state函数的参数是一个数组,所以做这样的事情

{
    ...state,
    reduxArray : [action.payload , ...state.reduxArray]
}

...state由于没有密钥,将导致错误。可能这是你想要的形状

case 'POPULATEARRAY': 
    return [action.payload , ...state.reduxArray]

推荐阅读