为什么redux州改变另一个州?

时间:2017-12-24 13:17:51

标签: reactjs redux

谁可以解释为什么在redux商店文章(数组)状态破坏我改变另一个状态(例如语言) 这是关于它的2个截图。 first screenshot

second screenshot

动作/语言

    import { SWITCH_LANG } from '../types';

// switch Language
export const setlocale = (lang) => (dispatch) => {
    localStorage.devsLang = lang;
    dispatch(setLocaleDispatch(lang))
}

export const setLocaleDispatch = (lang) => ({
    type: SWITCH_LANG,
    lang
})

减速器/语言

import { SWITCH_LANG } from '../types';

export default function locale(state = { lang: "en" }, action = {}) {
    switch(action.type) {
        case SWITCH_LANG:
            return { lang: action.lang }
        default:
            return state;
    }
}

one more screenshot from redux-logger

3 个答案:

答案 0 :(得分:0)

你覆盖你的州。您需要复制现有状态并添加新值。使用Object.assignspread operator,如下所示:

Object.assign({}, state, { lang: action.lang } )

更多信息here

答案 1 :(得分:0)

减速器/条

import { createSelector } from 'reselect';
import { ADD_NEW_ARTICLE, GET_ALL_ARTICLES, GET_ONE_ARTICLE } from '../types';

export default function article(state = {}, action = {}) {
    switch(action.type) {
        case ADD_NEW_ARTICLE:
            return action.article
        case GET_ALL_ARTICLES:
            return action.articles
        case GET_ONE_ARTICLE:
            return action.oneArticle
        default:
            return {};
    }
}

export const articlesHashSelector = state => state.article;

export const articlesSelector = createSelector(
    articlesHashSelector,
    hash => Object.values(hash)
);

答案 2 :(得分:0)

来自 redux-logger 屏幕截图

我可以告诉您返回数组文章,检查 GET_ALL_ARTICLES 操作的有效负载

case GET_ALL_ARTICLES: 
   return action.articles

所以基本上你正在改变文章状态。从对象到数组