javascript - 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 };
解决方案
你的函数 insReducer.js
不正确。该state
函数的参数是一个数组,所以做这样的事情
{
...state,
reduxArray : [action.payload , ...state.reduxArray]
}
...state
由于没有密钥,将导致错误。可能这是你想要的形状
case 'POPULATEARRAY':
return [action.payload , ...state.reduxArray]
推荐阅读
- nginx - 大文件上传到 nginx 失败
- php - 循环中的 PHP 异步请求
- python - NameError:名称“输出”未定义
- wordpress - Wordpress - 定制器设置覆盖以前的设置
- jquery - 如何替换除颜色代码字符串之外的哈希标签
- go - 是否可以在golang中创建进程池
- plsql - 使用 javascript 时没有删除记录 :(htmldb_delete_message,'DELETE');
- reactjs - ReactJS 教程:在哪里
来自? - django - Django:从查询集中删除辅助注释
- javascript - MomentJS 在以秒为单位格式化时间时返回 0