【发布时间】:2016-09-17 18:23:11
【问题描述】:
我对使用 redux、redux-immutable 和 immutablejs 的 react 应用程序中的状态发生了什么感到困惑。
我的减速器看起来像这样:
export const initialState = Map({
isFetching: false,
forecast: List()
});
export function forecast(state = initialState, action) {
switch(action.type) {
case ActionTypes.FORECAST.REQUEST:
return state.merge({
isFetching: true
});
case ActionTypes.FORECAST.SUCCESS:
return state.merge({
isFetching: false,
forecast: action.response
});
case ActionTypes.FORECAST.FAILURE:
return state.merge({
// isFetching: false
});
}
return state;
};
export function errorMessage(state = null, action) {
const { type, error } = action;
if (type === ActionTypes.RESET_ERROR_MESSAGE) {
return null;
} else if (error) {
return {errorMessage: action.error};
}
return state;
};
export default combineReducers({
forecast,
errorMessage,
routing: routerReducer
});
这是我创建商店的方式:
import reducers from '../reducers';
const initialState = Map();
const store = createStore(reducers,
initialState,
compose(
applyMiddleware(
thunkMiddleware,
logger
)
));
在一个连接的组件中,我将这个函数传递给连接:
function mapStateToProps(state) {
return {
forecast: state.get('forecast'),
isFetching: state.get('isFetching')
};
}
export default connect(mapStateToProps, {
fetchForecast
})(Forecast);
但是,如果我查看传递给 mapStateToProps 的状态
它看起来是由我结合以下代码的3个reducer组成的地图;
export default combineReducers({
forecast,
errorMessage,
routing: routerReducer
});
我可以将mapStateToProps 中的代码更改为:
function mapStateToProps(state = state.get('forecast')) {
return {
forecast: state.get('forecast').get('forecast'),
isFetching: state.get('forecast').get('isFetching')
};
}
但这感觉不对。为什么我的 state 是由 3 个 reducer 组成,而不是我在这里指定的初始 state:
export const initialState = Map({
isFetching: false,
forecast: List()
});
export function forecast(state = initialState, action) {
switch(action.type) {
case ActionTypes.FORECAST.REQUEST:
【问题讨论】:
标签: reactjs redux immutable.js