React Redux - does the state returned in mapStateToProps have reducer names as properties?

I have 2 gearboxes that are combined in Root Reducer and used in the store. The first AllTracksReducer reducer should return the object, and the second Favorite the array.

When I create a container component and a mapStateToProps method in a connection, for some reason, the return state of the store is an object with two gear objects that store data, and not just an object containing correction data, as expected.

    function mapStateToProps(state) {
       debugger:
       console.dir(state)
       //state shows as an object with 2 properties, AllTracksReducer and       FavoritesReducer. 


        return {
            data: state.AllTracksReducer.data,
            isLoading: state.AllTracksReducer.isLoading
        }
    }

export default connect(mapStateToProps)(AllTracksContainer);

therefore, in mapStateToProps, in order to get to the correct state of the state, I have to say state.AllTracksReducer.data ... But did I expect the data to be available directly to the state object?

+4
3

, -. , ES6 , , combineReducers, .

Redux, - combineReducers.

+1

, ( , ), mapStateToProps. , , , combineReducers , :

const getTracks = (state) => state.allTracks.data
const isLoading = state => state.allTracks.isLoading

, allTracks, :

combineReducers({
  allTracks: allTracksReducer
})

,

const mapStateToProps = state => ({
  isLoading: isLoading(state),
  tracks: getTracks(state)
})

combineReducers . , .

"" "", . ( ), , , , .

+1

, . combReducers, .

If this bothers you, I would suggest some syntactic magic if you are using es2016 (although it seems like it is not):

function mapStateToProps(state) {
    const { data, isLoading } = state.allTracksReducer;
    return {
        data: data,
        isLoading: isLoading
    }
}

export default connect(mapStateToProps)(AllTracksContainer);

Remember that state is the only source of truth that has all your gearboxes.

0
source

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


All Articles