[英]How to combine 2 reducers right with combineReducers?
因此,我试图弄清楚combineReducers
工作方式,但是现在我不明白为什么我无法在减速器loadMore
更新时根据减速器weather
设置当前state
。
PS在减速机weather
新状态正常推送。
减速器天气:
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;
减速机LOAD-MORE:
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;
减速机INDEX:
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;
集装箱装载更多:
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);
容器WeatherLayout:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import WheatherLayoutComponent from '../components/WheatherLayout'
const mapStateToProps = state => (console.log('WheatherLayoutComponent ', state), {
cityStore: state.weather
});
export default connect(
mapStateToProps,
null)(WheatherLayoutComponent);
为了澄清一点,我将您的reducer重命名为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)
。 因此,在mapStateToProps
映射state
相关部分时,应调用state.loadMore
。
const mapStateToProps = state => (console.log('loadMoreComponent', state), {
state: state.loadMore // not state.weather
});
这就是我从您发布的代码部分中可以获得的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.