我有登录页面组件,其中我有一个名为isUserAuthenticated的布尔状态,当我点击登录按钮时,检查用户是否存在的用户列表。用户列表在signupreducer中,如何访问loginreducer中的用户列表并从中返回isUserAuthenticated标志。
登录页面组件
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 :(得分:2)
我假设你正在使用combineReducers
设置状态树。您需要编写一个自定义组合函数,将您需要的状态(从注册)传递到登录减速器。
在redux文档中有一个如何执行此操作的示例:http://redux.js.org/docs/recipes/reducers/BeyondCombineReducers.html#sharing-data-between-slice-reducers
答案 1 :(得分:0)
如果您不想在Reducer之间共享数据,还有另一种方式。要完成此操作,请使用getState
并在您要发送到需要它的reducer的操作中包含您需要的状态。以下是一个示例: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
}
});
}
}
答案 2 :(得分:0)
我做过这样我现在可以访问并且它正在运行,任何人都建议我这是一种正确的做法。
export const mapStateToProps = (state) => {
return {
isUserAuthenticated: state.reducer.isAuthenticated.isUserAuthenticated,
users: state.SignupReducer.users
}
}
这里我在mapStateToProps中选择了另一个reducer状态然后我在我的点击事件中准备了一个类
onLogin = () => {
var credentials = {
username: this.userName,
password: this.password
}
var loginFormData ={
credentials:credentials,
users:this.props.users
}
this.props.checkLogin(loginFormData);
}
最后,我将使用登录表单的凭证和其他reducer的状态发送我的操作
export const mapDispatchToProps = (dispatch) => {
return {
checkLogin: (loginFormData) => dispatch({ type: 'CHECK_LOGIN', loginFormData })
}
};