加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 如何在一个状态内合并多个Reducer?

发布时间:2020-12-15 05:07:40 所属栏目:百科 来源:网络整理
导读:我正在尝试构建一个应用程序,该应用程序有两个或更多个reducer“回答”我的storeState中的一个对象. 例: storeState { app: {...},comments: [ ...two or more states inside one... ]} 我已经尝试了以下使用不起作用的combineReducers,我的注释状态变成了
我正在尝试构建一个应用程序,该应用程序有两个或更多个reducer“回答”我的storeState中的一个对象.

例:

storeState {
    app: {...},comments: [ ...two or more states inside one... ]
}

我已经尝试了以下使用不起作用的combineReducers,我的注释状态变成了一个空对象.

import { combineReducers } from 'redux';
import commentFacebookReducer from './twitch';
import commentYoutubeReducer from './reddit';
import appReducer from './app';

const rootReducer = combineReducers({
  comments: [commentFacebookReducer,commentYoutubeReducer],app: appReducer
});

export default rootReducer;

我已经尝试将我的评论缩减器组合在一起,然后将它们组合在rootReducer中:

import { combineReducers } from 'redux';
import commentFacebookReducer from './twitch';
import commentYoutubeReducer from './reddit';
import appReducer from './app';

const commentReducers = combineReducers({
  commentFacebookReducer,commentYoutubeReducer
});

const rootReducer = combineReducers({
  comments: commentReducers,app: appReducer
});

export default rootReducer;

但它给了我一个像以下那样的storeState.但我需要一个注释数组的状态,我不能处理这些减少名称(如commentFacebookReducer或commentYoutubeReducer),因为我会有数千个这样的减速器.

storeState {
    app: {...},comments: {
        commentFacebookReducer: {...},commentYoutubeReducer: {...}
    }
}
我不认为你可以通过使用combineReducer来做到这一点.因为combineReducer需要一个对象,该对象的每个属性都应该是
一个功能.然后该对象中的每个函数在redux状态树中创建一个单独的属性,该属性的值是该函数返回的值(当调度任何操作时).

此外,您无法在其他reducer中访问一个reducer的状态,因为redux仅将该特定reducer的状态传递给该函数.这意味着你无法在commentYoutubeReducer中获取/更改commentFacebookReducer的状态.

我现在能想到的唯一更好的解决方案是在使用它们时将它们组合在一起(最有可能在mapStateToProps中).你保持你的减速器就像你这样做:

const commentReducers = combineReducers({
  commentFacebookReducer,app: appReducer
});

现在我们所有的评论都在一个对象中,即(state.comments).现在在mapStateToProp中你可以做这样的事情,将它们组合在一个对象中::

const mapStateToProps = state => {
    return {
        comments: Object.keys(state.comments).reduce((d,k) => {return d.concat(a[k])},[] )
    };
};

现在在组件中,您可以使用this.props.comments将它们作为单个数组进行访问

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读