redux从后端获得数据怎么传递给state

比如一个博客,首次进入页面,我从后端同时获得了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就行。
不知是否合理。

阅读 3.6k
3 个回答

更好的方式是合并成一个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的习惯写法

const data = {article, user, comment}

action.js

const xxx = data => ({ type: XXX, data })

reducer.js

function xxx(state, action) {
  switch (action.type) {
    case 'XXX':
      return Object.assign({}, state, {
        article: state.data.article,
        user: state.data.user,
        comment: state.data.comment
      })
    default:
      return state
  }
}
新手上路,请多包涵

createStore第二个参数可以带默认state

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题