一个简单的问题:我有两个组件,有两个reducer。基本上分为两部分的申请的状态将类似于{stateComponent1: object, stateComponent2: object ....}.
Component2
,此外,“使用”第一组件的状态,这由MapStateToProps
函数完成,其中我们将stateComponent1
和stateComponent2
(“拥有”)。React&Redux传播状态变化
的问题是,当Component1
进行使stateComponent1
改变,Component2
应重新呈现调度,因为它在它的道具stateComponent1
?关键是这不会发生。
编辑:我告诉你我的代码
我有一个店,做的登录,基本上是这样的:
行动
export const actionCreators = {
requestLogin: (credentials: Credentials): AppThunkAction<KnownAction> => (dispatch, getState) => {
dispatch({
type: 'LOGIN_REQUEST',
isFetching: true,
isAuthenticated: false,
credentials: credentials
});
const config = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `username=${credentials.username}&password=${credentials.password}`
};
const loginTask = fetch(`http://localhost:50679/api/jwt`, config).then(response => response.json()).then((data) => {
if (!data.idToken) {
dispatch({
type: 'LOGIN_FAILURE',
isFetching: false,
isAuthenticated: false,
message: 'Error en el login'
});
return Promise.reject(data);
} else {
// If login was successful, set the token in local storage
if (typeof localStorage !== 'undefined') {
localStorage.setItem('idToken', data.idToken);
}
// Dispatch the success action
dispatch({
type: 'LOGIN_SUCCESS',
isFetching: false,
isAuthenticated: true,
idToken: data.idToken
});
}
});
},
REDUCERS:
export const reducer: Reducer<LoginState> = (state: LoginState, action: KnownAction) => {
switch (action.type) {
case 'LOGIN_REQUEST':
return {
isFetching: true,
isAuthenticated: false,
idToken: '',
credentials: action.credentials,
message: ''
};
case 'LOGIN_SUCCESS':
return {
isFetching: false,
isAuthenticated: true,
idToken: action.idToken,
credentials: null,
message: ''
};
case 'LOGIN_FAILURE':
return {
isFetching: false,
isAuthenticated: false,
idToken: '',
credentials: null,
message: action.message
};
case 'LOGOUT_SUCCESS':
return {
isFetching: true,
isAuthenticated: false,
idToken: '',
credentials: null,
message: ''
};
default:
// The following line guarantees that every action in the KnownAction union has been covered by a case above
const exhaustiveCheck: any = action;
}
return state || unloadedState;
};
现在,我有一个订阅登录状态的组件,当这个状态改变时它必须“找出” S,即,例如,当登录完成后,我这样做:
return connect(
(state: ApplicationState) =>
Object.assign(state.login, state.location, state.history)
)(AuthenticatedComponent);
的问题是,当state.login改变了我的AuthenticationComponent组件不知道。
我不确定我的理解 - 如果组件2使用'stateComponent1',那么组件2应该在状态段改变时重新呈现是否合理? –
好吧,假设component1的状态段是组件2的道具的一部分,所以我知道当它改变时(通过Component 1派发),组件2应该被重新渲染,对吗?至少那是我认为 –
你能分享你的reducer的代码吗? – Faris