【发布时间】:2017-06-06 15:25:46
【问题描述】:
我正在使用 lodash 和 redux/react 来制作一个简单的应用程序。现在我让它返回一个包含多个对象的对象。所以当我得到最终的对象时,它看起来像这样。
对象{ 2:对象,34:对象}
每个对象都有一个标题、ID 和描述。我使用 lodash 映射键并使单个对象中的每个对象都以 ID 为键。这样更容易找到每个对象。例如 Mainobject[34] 将返回该对象,即使它在 Object 中是第二个。
所以现在一切正常,我希望能够更新对象或编辑一些代码并替换其中一个删除的对象。我正在使用 redux/react,因此需要理解这一点才能理解我想要做什么。
如您所见,我尝试使用 _.get 从 mainObject 中查找项目,然后使用 _.merge 更新该特定项目,然后我尝试使用 _.update,但在我的控制台中我当前状态的 .log 我在控制台中得到了这个:
当前状态是:-> Object {2: Object, 34: Object}
当前状态是:-> Object {2: Object, 34: Object, object Object: undefined}
第二个控制台有 id 为 34 的对象,一切都已更新并正常工作,但最后我得到的是未定义的对象 Object。
这是我的减速器:
const reducer = function(state={}, action) {
switch(action.type) {
case "POST_BOOK":
return _.mapKeys(action.payload, 'id');
break;
case "DELETE_BOOK":
return _.omit(state, action.payload);
break;
case "UPDATE_BOOK":
let foundItem = _.get(state, action.payload.id);
let updateItem = _.merge(state[action.payload.id],foundItem,action.payload);
console.log(updateItem);
return _.update(state, state[action.payload.id], updateItem);
break;
}
return state
}
这是我的行动:
store.dispatch({
type: "POST_BOOK",
payload: [
{
id: 34,
title: 'this is the book title',
description: 'this is the book description',
price: 3
},
{
id: 2,
title: 'this is the book title 2',
description: 'this is the book description 2',
price: 3.2
}
]
});
// store.dispatch({
// type: "DELETE_BOOK",
// payload: 2
// });
store.dispatch({
type: "UPDATE_BOOK",
payload: {
id: 34,
title: 'this is book edit title',
description: 'this is book edit edit',
price: 2341.23
}
})
【问题讨论】:
-
_.update的最后一个参数应该是一个函数(lodash.com/docs/4.17.4#update),这里传递一个对象。这可能是我认为的问题 -
有没有办法获取函数并让它更新被选中的对象?
-
看看你的代码,我想你只需要
return updateItem(也许重命名,我不知道)。它似乎包含您需要的所有信息,我错了吗? -
哦不,等等,它只有更新的项目,抱歉。但我们离解决方案并不遥远。那我可能会给你一个答案:)
标签: javascript reactjs redux lodash