一個簡單的問題:我有兩個組件,有兩個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