在尝试理解gillisd/react-router-v4-redux-auth中的react / redux代码时,我对state.auth.authenticated
返回的状态mapStateToProps
感到困惑。
例如,如果用户使用表单登录,
/client/src/components/auth/signin.js
class Signin extends Component {
handleSubmit({email, password}) {
this.props.signinUser({email, password});
}
提交表单会导致signinUser
函数调度type: AUTH_USER
export function signinUser({email, password}) {
return function (dispatch) {
// submit email and password to server
const request = axios.post(`${ROOT_URL}/signin`, {email, password})
request
.then(response => {
// -if request is good, we need to update state to indicate user is authenticated
dispatch({type: AUTH_USER})
触发reducer更新状态
/client/src/reducers/auth_reducer.js
export default function authReducer(state = {}, action) {
switch (action.type){
case AUTH_USER:
return {...state, error: '', authenticated: true};
问题:为什么{...state, error: '', authenticated: true}
将state.auth.authenticated
更新为true
而不是将state.authenticated
更新为true
?
我猜state.auth.authenticated
已更新为true
,因为下面的代码通过state.auth.authenticated
访问它。这是为什么?
/client/src/components/auth/signin.js
function mapStateToProps(state) {
return {
authenticated: state.auth.authenticated,
errorMessage: state.auth.error
}
}
答案 0 :(得分:2)
由于index.js
中的combineReducers
。
当您致电combineReducers
时,您将所有减速器合并为用于构建商店的单个减速器。但是,传递给combineReducers
的每个单独的缩减器仅控制其状态片。因此,因为您在密钥下面传递了authReducer
:
auth: authReducer
传递给authReducer
的第一个参数是state.auth
。 authReducer
基本上只管理状态的auth
键 - 它的状态切片。因此,当authReducer
返回新状态时,它会更新其切片state.auth
,而不只是state
本身。因此,state.auth.authenticated
已更改,而非state.authenticated
。这在documentation:
combineReducers()
生成的状态将每个reducer在其键下的状态命名为传递给combineReducers()
同样,redux-form
reducer只会修改state.form
,因为它根据其键控制state.form
状态片段。
答案 1 :(得分:1)
在combineReducers
index.js
内,authReducer已命名为auth
,因此状态可以state.auth.XXX
查看https://github.com/gillisd/react-router-v4-redux-auth/blob/master/client/src/reducers/index.js