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

查看:144
本文介绍了javascript - 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就行。
不知是否合理。

解决方案

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

这篇关于javascript - redux从后端获得数据怎么传递给state的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆