在尝试理解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调度动作

/client/src/actions/index.js

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})


触发减速器更新状态

/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
  }
}

最佳答案

由于combineReducers中的index.js

调用combineReducers时,将所有化简器组合到一个用于构建商店的简化器中。但是,传递给combineReducers的每个单独的reducer只能控制其状态片。因此,由于要在键下传递authReducer

auth: authReducer


传递给authReducer的第一个参数是state.authauthReducer本质上仅控制状态的auth键-状态键。因此,当authReducer返回新状态时,它将更新其切片state.auth,而不仅仅是state本身。因此,state.auth.authenticated被更改,而不是state.authenticateddocumentation中提到了这一点:


  combineReducers()产生的状态命名空间在传递给combineReducers()的键下每个化简器的状态


同样,redux-form缩减器将仅修改state.form,因为它根据其键控制state.form状态片。

08-05 18:27