我在做reactjs,所以我需要立即更新一个字段来触发状态更改。我有这个有效载荷(只显示1,但它是许多的数组) [ { id: 1, name: "Fridge2", selected: true, sharingId: 'ae9b9566-3b5c-4772-a0a1-07ed8b354b8f', sharingWith: ["[email protected]", "[email protected]"], storageItems: [ { id: 'ae9b9564-3b5c-2711-a421-07ed8b354b8f', name: 'Chicken Breats', qty: 10, expiresOn: '3', category: 'Meat', categoryId: 'BDEC0494-B16E-411B-8E32-A64A00E943F8', unitType: 'Pieces', unitTypeId: '63CDB076-C20D-4DC5-A181-A64A00E94409' }, { id: 'ae9b9566-3b5c-2711-a4a1-07ed8b354b8f', name: 'Chicken Breats2', qty: 10, expiresOn: '0', category: 'Meat', categoryId: 'BDEC0494-B16E-411B-8E32-A64A00E943F8', unitType: 'Pieces', unitTypeId: '63CDB076-C20D-4DC5-A181-A64A00E94409' }, { id: 'ae9b9566-3b5c-2712-a0a1-07ed8b354b8f', name: 'Chicken Breats3', qty: 10, expiresOn: '4', category: 'Meat', categoryId: 'BDEC0494-B16E-411B-8E32-A64A00E943F8', unitType: 'Pieces', unitTypeId: '63CDB076-C20D-4DC5-A181-A64A00E94409' } ] }]我想找到与ID'ae9b9564-3b5c-2711-a421-07ed8b354b8f'(数组中的第一个)匹配的storageItem然后,我想将其取出来更新字段(例如,数量)并重新插入并发生状态更改。这是我非常糟糕的第一次尝试。这没用case actions.STORAGE_ITEM_USED: { var foundItem = state.selectedStorage.storageItems.filter(i => i.id == action.payload); var newQty = foundItem[0].qty - 1; foundItem[0].qty = newQty; var nonChangedStorageItem = state.selectedStorage.storageItems.filter(i => i.id != action.payload); var allItems = nonChangedStorageItem.concat(foundItem); state.selectedStorage.storageItems = allItems; return { selectedStorage: state.selectedStorage, } }编辑我现在有这个,但我看到了一个新的可能答案,我将结帐var newSelectedStorage = Object.assign({} , state.selectedStorage); var foundItem = newSelectedStorage.storageItems.filter(x => x.id == action.payload); foundItem[0].qty = foundItem[0].qty - 1; var nonChangedItems = newSelectedStorage.storageItems.filter(x => x.id != action.payload); newSelectedStorage.storageItems = nonChangedItems.concat(foundItem);webpack.config.jsmodule.exports = { devtool: 'inline-source-map', entry: "./app/index.js", output: { path: __dirname + '/dist', filename: "bundle.js" }, devServer: { contentBase: "./app", inline: true, port: 3333 }, module: { loaders: [ { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['es2015', 'react'] } }, { test: /\.scss$/, loaders: ['style', 'css', 'sass'] }, { test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/, loader: 'url-loader' } ] }, externals: { jquery: 'jQuery' },} 最佳答案 从外观上看,您试图减小qty中任何匹配对象的state.selectedStorage.storageItems属性。由于Redux需要一个全新的对象,因此我们可以使用ES6的对象散布运算符返回已经填充了大多数值的新对象。case actions.STORAGE_ITEM_USED: return { ...state, selectedStorage: state.selectedStorage.storageItems.map(i => { if (i.id != action.payload) return i; return { ...i, qty: i.qty - 1 } }) }我无法测试这种方法是否可行,但是我们的想法是我们要返回一个新对象,复制现有状态对象,然后用新数组覆盖selectedStorage,其中只有id与action.payload匹配的属性降低。关于javascript - 如何更新Json对象数组中的一个字段?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38924436/
10-12 16:28