比如一个博客,首次进入页面,我从后端同时获得了user,article,comment,我是一个一个传递给他们吗?就像这样const article = (article) => ({type: 'INIT_ARTICLE', article});const user = (user) => ({type: 'INIT_USER', user});const comment = (user) => ({type: 'INIT_COMMENT', comment});获取后触发三个dispatch吗?目前我的做法const blogReducer = (state = {}, action) => { switch (action.type) { case RECEIVE_DATA: return action.data; default: return { comment: commentHelper(state.comment, action), article: articleHelper(state.article, action), user: userHelper(state.user, action), } }} const commentHelper = (state = [], action) => { switch (action.type) { case 'ADD_COMMENT': return [...state, action.comment]; default: return state; } }获取数据时触发RECEIVE_DATA,更改comment时,触发ADD_COMMENT就行。不知是否合理。
1 回答
MMMHUHU
TA贡献1834条经验 获得超8个赞
更好的方式是合并成一个dispatch:
const data = (user, article, comment) => ({type: 'INIT_BLOG', data: {user, article, comment}})
dispatch 这个Action
reducer:
const blogReducer = (state = {}, action) => {
switch (action.type) {
case 'INIT_BLOG':
return {...state,
comment: action.data.comment,
article: action.data.article,
user: action.data.user
};
case 'ADD_COMMENT':
return {...state, comment: [...state, action.data.comment]};
default:
state;
}
}
你上面的写法功能是可以的,但不符合reducer的习惯写法
添加回答
举报
0/150
提交
取消