2017-07-25 80 views
0

我有登錄頁面組件,其中我有一個布爾狀態稱爲isUserAuthenticated,當我點擊登錄按鈕,檢查userslist是否用戶是否存在。用戶列表在signupreducer中,我如何訪問loginreducer中的用戶列表並從中返回isUserAuthenticated標誌。如何訪問其他reducer減速器的狀態減少

LoginPage組件

export const mapStateToProps = (state) => { 
    return { 
     isUserAuthenticated: state.reducer.isAuthenticated.isUserAuthenticated, 
     users: state.SignupReducer.users 
    } 
} 

export const mapDispatchToProps = (dispatch) => { 
    return { 
     checkLogin: (credentials) => dispatch({ type: 'CHECK_LOGIN', credentials }) 
    } 
}; 

LoginPage = connect(mapStateToProps, mapDispatchToProps)(LoginPage); 

export default LoginPage; 

登錄減速

const initialStateAuth = { 
    isUserAuthenticated: false 
}; 

export const isAuthenticated = (state = initialStateAuth, action) => { 
    switch (action.type) { 
     case 'CHECK_LOGIN': 
      return Object.assign({}, state, { isUserAuthenticated: checkLogin(state, action) }) 
     default: 
      return state; 
    } 
} 

這裏其實我想檢查用戶在 singupReducer.users我怎麼可以在這裏訪問....

const checkLogin = (state, action) => { 
    let isExist = false; 
    signupReducer.users.map((each) => { 
     if (each.userName === action.credentials.username && each.password === action.credentials.password) { 
      isExist = true; 
     } 
    }); 
    return state.isUserAuthenticated = false; 

} 
+0

看來你有拼寫問題。有時你使用'singupReducer'或'SignupReducer'。 –

+0

@DamienGold有史以來什麼,但我只用在一個地方,這不是我剛纔提到的「signupReducer」。我的問題是我怎樣才能訪問其他reducer狀態在特定的reducer。謝謝 – kumar

回答

0

還有另外一種方式,如果你不想減速器之間共享數據。爲了達到這個目的,你可以使用getState,並且在你發送給需要它的減速器的動作中加入你需要的狀態。這裏有一個例子:Alternative to sharing data between slice reducers

function someSpecialActionCreator() { 
    return (dispatch, getState) => { 
     const state = getState(); 
     const dataFromB = selectImportantDataFromB(state); 

     dispatch({ 
      type : "SOME_SPECIAL_ACTION", 
      payload : { 
       dataFromB 
      } 
     }); 
    } 
} 
+0

有沒有辦法做到這一點,而不寫任何自定義函數 – kumar

+0

不寫任何自定義函數?否:(你至少需要'mapDispatchToProps','連接'你的組件,有'actionCreators'和'reducer'來處理狀態更新。 –

0

我不喜歡這樣我可以現在訪問和它的工作,任何人都建議我是這樣做的正確方法。

export const mapStateToProps = (state) => { 
    return { 
     isUserAuthenticated: state.reducer.isAuthenticated.isUserAuthenticated, 
     users: state.SignupReducer.users 
    } 
} 

在這裏,我選擇了mapStateToProps其他減速狀態的話,我在我的單擊事件準備下課這樣

onLogin =() => { 
     var credentials = { 
      username: this.userName, 
      password: this.password 
     } 
     var loginFormData ={ 
      credentials:credentials, 
      users:this.props.users 
     } 
     this.props.checkLogin(loginFormData); 
    } 

最後我正在我的派遣行動,登錄credentilas形式和狀態

export const mapDispatchToProps = (dispatch) => { 
    return { 
     checkLogin: (loginFormData) => dispatch({ type: 'CHECK_LOGIN', loginFormData }) 
    } 
};