在Redux的reducers中更新state的正确方法
在Redux的reducers中更新state的正确方法
我是一个redux和es6语法的新手。我使用官方的redux教程和这个示例来创建我的应用程序。
下面是一个JS片段。我的重点是在posts reducer中定义REQUEST_POST_BODY和RECEIVE_POST_BODY两个case。
主要困难是找到并更新存储中的正确对象。
我尝试使用示例中的代码:
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}] } // posts存储的reducer export default function posts(state = initialState, action) { switch (action.type) { case REQUEST_POST_BODY: // 在这里我需要设置post.isFetching => true case RECEIVE_POST_BODY: // 在这里我需要设置post.isFetching => false和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'}));