我有两个减速器,它们共享一些动作。问题是,当我在一个屏幕上调度动作时,它将在另一屏幕上触发动作。两个屏幕都在TabNavigator中,因此我可以很容易地看到,如果我在一个屏幕上更改了一个字段,则在另一个屏幕上也更改了相同的字段。
Reducer 1
import * as Actions from '../actions/Types';
const initialState = {
email: '',
password: ''
};
const signInReducer = (state = initialState, action) => {
switch(action.type) {
case Actions.CHANGE_EMAIL_INPUT:
return Object.assign({}, state,
{ email: action.email }
);
case Actions.CHANGE_PASSWORD_INPUT:
return Object.assign({}, state,
{ password: action.password }
);
default:
return state;
}
}
export default signInReducer;
Reducer 2
import * as Actions from '../actions/Types';
const initialState = {
firstName: '',
lastName: '',
email: '',
password: '',
repeatPassword: ''
};
const signUpReducer = (state = initialState, action) => {
switch(action.type) {
case Actions.CHANGE_FIRST_NAME_INPUT:
return Object.assign({}, state,
{ firstName: action.firstName }
);
case Actions.CHANGE_LAST_NAME_INPUT:
return Object.assign({}, state,
{ lastName: action.lastName }
);
case Actions.CHANGE_EMAIL_INPUT:
return Object.assign({}, state,
{ email: action.email }
);
case Actions.CHANGE_PASSWORD_INPUT:
return Object.assign({}, state,
{ password: action.password }
);
case Actions.CHANGE_REPEAT_PASSWORD_INPUT:
return Object.assign({}, state,
{ repeatPassword: action.password }
);
default:
return state;
}
}
export default signUpReducer;
商店
import { createStore, combineReducers } from 'redux';
import signInReducer from '../reducers/SignIn';
import signUpReducer from '../reducers/SignUp';
import profileReducer from '../reducers/Profile';
const rootReducer = combineReducers({
signIn: signInReducer,
signUp: signUpReducer,
profile: profileReducer
});
const configureStore = () => {
return createStore(rootReducer);
}
export default configureStore;
如您所见,有一些常见的动作,例如 CHANGE_EMAIL_INPUT 和 CHANGE_PASSWORD_INPUT ,我不希望它们一起触发。我可以弄清楚的一种方法是更改操作的名称,然后使其更具体地针对屏幕,但这听起来并不好。另一个可能是包装减速器,以便我们知道正在调用什么,但在包装器上却不了解。
任何建议。
答案 0 :(得分:1)
您不应在两个reducer之间重用相同的动作名称,为避免意外的效果,请使用不同的名称。
例如
Actions.SIGNUP_ CHANGE_EMAIL_INPUT
和
Actions.SIGNIN_ CHANGE_EMAIL_INPUT
否则,您可以合并2个reducer,并添加一个状态以了解此更改从哪个屏幕出现。
答案 1 :(得分:0)
好吧,我为减速器创建了一个包装器。
商店
function createNamedWrapperReducer(reducerFunction, reducerName) {
return (state, action) => {
const isInitializationCall = state === undefined;
const shouldRunWrappedReducer = reducerName(action) || isInitializationCall;
return shouldRunWrappedReducer ? reducerFunction(state, action) : state;
}
}
const rootReducer = combineReducers({
// signIn: signInReducer,
// signUp: signUpReducer,
// profile: profileReducer
signIn: createNamedWrapperReducer(signInReducer, action => action.name === 'signIn'),
signUp: createNamedWrapperReducer(signUpReducer, action => action.name === 'signUp'),
profile: createNamedWrapperReducer(profileReducer, action => action.name === 'profile'),
});
屏幕
onChangeEmail: (email) => { dispatch({name: 'signIn', type: Actions.CHANGE_EMAIL_INPUT, email: email}) },