我正在尝试在减速器中更新嵌套数据。使用以下操作,我将在我的reducer中返回一个数组映射。但是我的状态没有改变:
case "SUBMIT_ANSWER":
const { current, results, completed } = action.data;
return state.map(video =>
video.id === action.id
? { ...video, current, results, completed }
: video
);
操作:
{
type: "SUBMIT_ANSWER", data: {…}}
data:
completed: false
current: 1
id: 142
results: {correctAnswers: 1, score: 5}
}
需要更新的数据:
{
videos: [{
bookMarked: false
completed: false
correctScore: 5
current: 0
description: "<p>Lorem ipsum dolor sit amet</p>↵"
iconPath: "require('../assets/images/venepuncture.png')"
id: 142
preview: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut"
questions: (15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
results: {score: 0, correctAnswers: 0}
title: "Venepuncture"
totalScore: 50
youtubeVideo: "cxcxcx"
}
......
]}
答案 0 :(得分:0)
假设
var state = {
videos: [...]
}
您必须使用Object.assign
来获取具有所需更改的新状态对象(请勿更改原始状态)
const { current, results, completed } = action.data;
return Object.assign({}, state, {
videos: state.videos.map(...)
});
答案 1 :(得分:0)
假定以下嵌套状态:
#include <algorithm>
#include <iostream>
#include <vector>
#include <iterator>
#include <range/v3/view/filter.hpp>
#include <range/v3/view/transform.hpp>
int main()
{
std::vector<int> items = { 1, 3, 6, 8, 13, 17 };
std::vector<int> subitems = { 3, 6, 17 };
auto predicate = [&](int& n){
for(auto& s : subitems)
if(n == s)
return true;
return false;
};
auto result = items | ranges::view::filter(predicate);
for (auto& n : result)
{
std::cout << n << '\n';
}
for(auto it = result.begin(); it != result.end(); ++it )
std::cout << it.base() - items.begin() << ' ';
}
现在,假设您要更新{
itemA: 'bla',
name: [
{a: 2, b:3, value:'John', lannguages:['pt','en']}
],
obj:{
obj2:{
nestedArray : [1,2,3]
}
}
}
动作的nestedArray
道具,并以UPDATE_ARRAY
的形式传递数字,以进行合并:
action.data
只需按正确的顺序使用点差运算符,就可以了!