【发布时间】:2016-07-02 02:11:57
【问题描述】:
我是 redux 和 es6 语法的新手。我使用官方 redux 教程和 example 制作我的应用程序。
下面有JS sn-p。我的观点 - 在 post reducer 中定义 REQUEST_POST_BODY 和 RECEIVE_POST_BODY 案例。 主要困难 - 在商店中找到和更新正确的对象。
我尝试使用示例中的代码:
return Object.assign({}, state, {
[action.subreddit]: posts(state[action.subreddit], action)
})
但它使用了简单的帖子数组。不需要按id找合适的帖子。
这是我的代码:
const initialState = {
items: [{id:3, title: '1984', isFetching:false}, {id:6, title: 'Mouse', isFetching:false}]
}
// Reducer for posts store
export default function posts(state = initialState, action) {
switch (action.type) {
case REQUEST_POST_BODY:
// here I need to set post.isFetching => true
case RECEIVE_POST_BODY:
// here I need to set post.isFetching => false and post.body => action.body
default:
return state;
}
}
function requestPostBody(id) {
return {
type: REQUEST_POST_BODY,
id
};
}
function receivePostBody(id, body_from_server) {
return {
type: RECEIVE_POST_BODY,
id,
body: body_from_server
};
}
dispatch(requestPostBody(3));
dispatch(receivePostBody(3, {id:3, body: 'blablabla'}));
【问题讨论】:
-
如果
ids 总是唯一的,最好将items设为对象而不是数组。然后你可以使用items[id]通过id找到。
标签: javascript reactjs redux flux