這聽起來像一個偉大的使用情況爲.map()
陣列方法。
假設你的數據是這樣的:
var todos = [
{
id: 1,
title: 'Todo 1 Title',
body: 'Todo 1 Body',
date: 1425364758,
comments: [
{
id: 1,
commentorId: 42069,
text: 'Todo 1, Comment 1 Text',
date: 1425364758
},
{
id: 2,
commentorId: 42069,
text: 'Todo 1, Comment 2 Text',
date: 1425364758
},
{
id: 3,
commentorId: 42069,
text: 'Todo 1, Comment 3 Text',
date: 1425364758
}
]
},
{
id: 2,
title: 'Todo 2 Title',
body: 'Todo 2 Body',
date: 1425364758,
comments: [
{
id: 1,
commentorId: 42069,
text: 'Todo 2, Comment 1 Text',
date: 1425364758
}
]
},
{
id: 3,
title: 'Todo 3 Title',
body: 'Todo 3 Body',
date: 1425364758,
comments: [
{
id: 1,
commentorId: 42069,
text: 'Todo 3, Comment 1 Text',
date: 1425364758
},
{
id: 2,
commentorId: 42069,
text: 'Todo 3, Comment 2 Text',
date: 1425364758
}
]
}
];
當更新註釋,你需要在todoId
傳遞和commentId
讓你知道要尋找什麼。當添加註釋,你只需要在一個todoId
傳遞,所以你知道哪些待辦事項更新:
const todoReducer = (todos = [], action) => {
switch(action.type) {
case 'ADD_TODO':
return [
action.todo,
...todos
];
case 'ADD_COMMENT':
const { todoId, comment } = action;
// Map through all the todos. Returns a new array of todos, including the todo with a new comment
return todos.map(todo => {
// Look for the todo to add a comment to
if (todo.id === todoId) {
// When the todo to update is found, add a new comment to its `comments` array
todo.comments.push(comment);
}
// Return the todo whether it's been updated or not
return todo;
});
case 'UPDATE_COMMENT':
const { todoId, commentId, commentText } = action;
// Map through all the todos. Returns a new array of todos, including the todo with the updated comment
return todos.map(todo => {
// First find the todo you want
if (todo.id === todoId) {
// Then iterate through its comments
todo.comments.forEach(comment => {
// Find the comment you want to update
if (comment.id === commentId) {
// and update it
comment.text = commentText;
}
});
}
// Return the todo whether it's been updated or not
return todo;
});
default:
return todos;
}
};
export default todoReducer;
至於你的有效載荷,你可以讓他們任何你想要的,他們會在創建你的動作創造者。例如,下面是給待辦事項一個唯一的ID,時間戳它ADD_TODO
的實現,發射行動之前添加一個空comments
數組:
import uuid from 'node-uuid';
const addTodo = ({title, body}) => {
const id = uuid.v4();
const date = new Date().getTime();
return {
type: 'ADD_TODO',
todo: {
id,
title,
body,
date,
comments: []
}
};
};
你ADD_COMMENT
行動的創建者可能是這個樣子:
import uuid from 'node-uuid';
const addComment = ({todoId, commentorId, commentText}) => {
const id = uuid.v4();
const date = new Date().getTime();
return {
type: 'ADD_COMMENT',
todoId,
comment: {
id,
commentorId,
date,
text: commentText
}
};
};
這是未經測試,但希望給你一個想法。
[Updeep](https://github.com/substantial/updeep)可以很容易地執行嵌套對象和數組的更新;我建議看看它。 –
http://stackoverflow.com/questions/37980109/react-redux-complex-deep-state-objects duplicate – xiaofan2406
@ xiaofan2406我檢查了一下,但我似乎無法把握好這個概念。如果你不能根據我提供的例子提供一個例子嗎?謝謝 –