[英]State updating in redux
我是redux和es6语法的新手。 这里的问题:
有一个包含多个帖子的应用。
const initialState = {
items: {
3: {title: '1984'},
6: {title: 'Mouse'},
19:{title: 'War and peace'}
}
}
应用收到了一系列喜欢的帖子ID:
dispatch(receiveLikedPosts(3, {id:3, ids: [3,6]}));
function receiveLikedPosts(ids) {
return {
type: LIKED_POSTS_RECEIVED,
ids
};
}
有一个职位减少者:
function posts(state = initialState, action) {
switch (action.type) {
case LIKED_POSTS_RECEIVED:
// here I need to update my posts state: post.liked => true (only 3 and 6 post)
default:
return state;
}
}
1)我必须更新我的减速器LIKED_POSTS_RECEIVED代码。 Dunno如何以正确的方式做到这一点。
2)多次调度事件是否正确? (每个喜欢的帖子发送一次)
这里的代码:
// action
let ids = [3,6]
for (let id of ids) {
dispatch({type: LIKE, id});
}
// reducers
function post(state, action) {
switch (action.type) {
case LIKE:
return Object.assign({}, state, {
liked: true
});
default:
return state;
}
}
function posts(state = initialState, action) {
switch (action.type) {
case LIKE:
return Object.assign({}, state, {
[action.id]: post(state[action.id], action)
});
default:
return state;
}
}
这让我感到困惑:
dispatch(receiveLikedPosts(3, {id:3, ids: [3,6]}));
function receiveLikedPosts(ids) {
return {
type: LIKED_POSTS_RECEIVED,
ids
};
}
您的函数receiveLikedPosts
仅接受一个参数,但您要传递两个参数。 而且我不确定{ id: 3, ids: [3, 6] }
应该做什么。 但是,这是我会做的:
初始状态和减速器:
const initialState = {
items: {
3: { title: '1984', liked: false },
6: { title: 'Mouse', liked: false },
19: { title: 'War and peace', liked: false }
}
};
function posts(state = initialState, action) {
switch (action.type) {
let newItems = {};
case LIKED_POSTS_RECEIVED:
// copy the current items into newItems
newItems = {...state.items};
// Loop through the liked IDs, set them to liked:true
action.ids.forEach((likedId) => {
newItems[likedId].liked = true;
});
// Return the new state
return {
...state,
items: newItems,
}
default:
return state;
}
}
动作创建者:
function receiveLikedPosts(ids) {
return {
type: LIKED_POSTS_RECEIVED,
ids,
};
}
最后,调度:
dispatch(receiveLikedPosts([3, 6]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.