了解Redux的Reducer存储状态

时间:2018-04-17 03:59:14

标签: javascript reactjs redux react-redux redux-thunk

在尝试理解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})

触发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
  }
}

2 个答案:

答案 0 :(得分:2)

由于index.js中的combineReducers

当您致电combineReducers时,您将所有减速器合并为用于构建商店的单个减速器。但是,传递给combineReducers的每个单独的缩减器仅控制其状态片。因此,因为您在密钥下面传递了authReducer

auth: authReducer

传递给authReducer的第一个参数是state.authauthReducer基本上只管理状态的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