How to combine several gearboxes within the same state?

I am trying to create an application in which two or morereducers "respond" with one object inside mine storeState.

Example:

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

I already tried using combReducers, which did not work, my state commentsbecame empty.

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;

And I already tried to combine my comment reducers before combining them into 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;

But this gives me a storeState as shown below. But I need a state that is an array of comments, I cannot handle these reducer names (e.g. commentFacebookReducer or commentYoutubeReducer) because I will have thousands of such reducers.

storeState {
    app: {...},
    comments: {
        commentFacebookReducer: {...},
        commentYoutubeReducer: {...}
    }
}
+4
2

, , combReducer. combReducer , . redux, - , ( - ).

, redux . , / commentFacebookReducer commentYoutubeReducer.

, , , , ( , mapStateToProps). , :

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

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

i.e. (state.comments). mapStateToProp - , ::

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

, this.props.comments

+1

, , :

 comments: [ array of Comment]

, , , :

comments: commentsReducer

Reducer :

import {commentYouTubeReducer} from 'X'
import {commentFacebookReducer} from 'Y'

const commentsReducer = (state = [], action) => {

    switch (action.type){
       case 'ADD_COMMENT':
         return [..state, 
                {
                  YouTubeComment: commentYouTubeReducer(undefined, action),
                  FacebookComment: commentFacebookReducer(undefined, action)
                }]

    }     
} 

, , , . , , , Reducer , . , YoutubeReducer, , :

 ...
 case 'UPDATE_COMMENT':
 ...
 { youtubeComment: commentYoutubeReducer(comment.youtubeCommnet, action) ... }

- , : https://codepen.io/haakenlid/pen/qZOVjV

+1

Source: https://habr.com/ru/post/1684018/


All Articles