假设我有下一个减速器:
export default (state = [], { type, payload }) => {
switch (type) {
case FETCH_POKEMONS:
const objeto = {};
payload.forEach((conexion) => {
objeto[conexion.name] = conexion
});
return objeto;
case FETCH_POKEMON:
return { ...state, ...payload }
default:
return state
}
}
我将有一个这样的CombineReducers:
export default combineReducers({
pokemons: pokemonReducers,
});
但是我想为pokemons
动作设置FETCH_POKEMONS
状态,为pokemon
acton设置另一个状态叫FETCH_POKEMON
。如何从一个化简文件导出combineReducers
中的两个状态?
答案 0 :(得分:1)
您的动作创建者似乎还不错。我将张贴我的减速器之一,以展示我是如何做的。
import {ONIX_LOGIN_LOADING,ONIX_LOGIN_SUCCESS,ONIX_LOGIN_FAILURE,
ONIX_CONNECTIONS_LOADING,ONIX_CONNECTIONS_SUCCESS,ONIX_CONNECTIONS_FAILURE,
ONIX_PRODUCT_LOADING,ONIX_PRODUCT_SUCCESS,ONIX_PRODUCT_FAILURE
} from "../actions/onix-actions";
const defaultState = {
login:[],
connections: [],
product: []
};
export default function(state = defaultState, action){
switch(action.type){
case ONIX_LOGIN_LOADING:
return {...state, loginLoading:true};
case ONIX_LOGIN_FAILURE:
return {...state, loginLoading:action.isLoaded};
case ONIX_LOGIN_SUCCESS:
return {...state, loginLoading:false, login:action.data};
case ONIX_CONNECTIONS_LOADING:
return {...state, connectionsLoading:true};
case ONIX_CONNECTIONS_FAILURE:
return {...state, connectionsLoading:false};
case ONIX_CONNECTIONS_SUCCESS:
return {...state, connectionsLoading:false, connections:action.data};
case ONIX_PRODUCT_LOADING:
return {...state, productLoading:true};
case ONIX_PRODUCT_FAILURE:
return {...state, productLoading:false, productTitle:false};
case ONIX_PRODUCT_SUCCESS:
return {...state, productLoading:false, product:action.data};
}
return state
}
我喜欢这种格式,因为我可以在我的减速器那部分的状态之外调用自己的变量。然后在联合减速机中,我有以下内容:
import books from './books';
import onix from './onix';
const rootReducer = combineReducers({
books,
onix
});
export default rootReducer;
现在我可以打电话给onix了: this.props.onix.login 要么 this.props.onix.productTitle 它将返回我想要的那部分项目的数据。那回答了你的问题吗?
编辑:这是我的减速器文件结构的屏幕截图
答案 1 :(得分:1)
这是反模式,最接近的方法是从文件中导出2个reducer,每个用例一个
export const reducer1 = (state = [], { type, payload }) => {
switch (type) {
case FETCH_POKEMONS:
const objeto = {};
payload.forEach((conexion) => {
objeto[conexion.name] = conexion
});
return objeto;
default:
return state
}
}
export const reducer2 = (state = [], { type, payload }) => {
switch (type) {
case FETCH_POKEMON:
return { ...state, ...payload }
default:
return state
}
}
答案 2 :(得分:1)
如果我正确理解了您的问题,则您有两个操作FETCH_POKEMONS
和FETCH_POKEMON
,并且希望他们更新两个不同的状态pokemons
和pokemon
分别。
pokemon
和pokemons
,它们分别管理各自的状态然后将这些reduce传递到CombineReducers中,以将它们组合为单个应用程序级reduce。我认为这很可能是您要寻找的东西。state.pokemon
时的先前值。