如何将2个减速器与combineReducers结合使用?

时间:2018-04-22 16:08:42

标签: javascript redux react-redux

所以,我试图找出combineReducers的工作原理,但现在我无法理解为什么我无法在reducer {{1}中设置reducer state中的当前weather当它被更新时。

P.S。 在reducer loadMore中,新状态正常推送。

reducer天气:

weather

reducer LOAD-MORE:

import * as types from '../constants/ActionsTypes'

let initialState = {
    city: '',
    weather: [],
    loadMore: 5
};

const weather = (state = initialState, action) => {
    switch (action.type) {
        case types.ADD_WEATHER:
            return Object.assign({}, state, {
                city: action.cityName,
                weather: [
                    ...action.cityWeather
                ],
                loadMore: 5
            });
        default:
            return state;
    }
}

export default weather;

reducer INDEX:

import * as types from '../constants/ActionsTypes'

let initialState = {
    city: '',
    weather: [],
    loadMore: 5
};

const loadMore = (state = initialState, action) => {
    switch (action.type) {
        case types.LOAD_MORE:
            return Object.assign({}, state, {
                ...state, // when I click 'load more' the state is empty
                loadMore: action.loadMore
            });
        default:
            return state;
    }
}

export default loadMore;

容器loadMore:

import * as types from '../constants/ActionsTypes'
import { combineReducers } from 'redux';
import weather from './addWeather';
import loadMore from './loadMore';

const reducers = combineReducers({
    weather,
    loadMore
});

export default reducers;

容器WeatherLayout:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { moreWeather } from '../actions'
import loadMoreComponent from '../components/loadMore'

const mapStateToProps = state => (console.log('loadMoreComponent', state), {
    state: state.weather
});

const mapDispatchToProps = dispatch => ({
   moreWeather: (loadMore) => dispatch(moreWeather(loadMore))
});

export default connect(
    mapStateToProps,
    mapDispatchToProps)(loadMoreComponent);

1 个答案:

答案 0 :(得分:0)

为了澄清一些事情我将你的减速机重命名为Reducer combineReducers的工作方式是接受一个对象,例如{ weather : weatherReducer, loadMore: loadMoreReducer}并返回一个将在表单中返回状态的reducer:

(state, action) => ({
   weather: weatherReducer(state, action)
   loadMore: loadMoreReducer( state, action)
})

这意味着state.weather将包含weatherReducer(state, action)次返回,state.loadMore将包含loadMoreReducer( state, action)的结果。因此,在state中映射mapStateToProps的相关部分时,您应该调用state.loadMore

const mapStateToProps = state => (console.log('loadMoreComponent', state), {
    state: state.loadMore // not state.weather
});

这是我从您发布的代码部分中获得的信息。