【问题标题】:Understanding Redux's Reducer storing State了解 Redux 的 Reducer 存储状态
【发布时间】:2018-09-26 22:10:27
【问题描述】:

在尝试理解 gillisd/react-router-v4-redux-auth 中的 react/redux 代码时,我对 mapStateToProps 返回的状态 state.auth.authenticated 感到困惑。

例如,如果用户使用表单登录,

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

【问题讨论】:

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


    【解决方案1】:

    因为combineReducers 中的index.js

    当您调用combineReducers 时,您会将所有reducer 组合成一个用于构建store 的reducer。但是您传递给combineReducers 的每个单独的reducer 只管理它的状态部分。因此,由于您在密钥下传递 authReducer

    auth: authReducer
    

    传递给authReducer 的第一个参数是state.authauthReducer 基本上只管理 auth 状态键——它的状态片。因此,当authReducer 返回新状态时,它会更新其切片state.auth,而不仅仅是state 本身。所以state.auth.authenticated 改变了,而不是state.authenticateddocumentation中提到了这一点:

    combineReducers() 产生的状态将每个 reducer 在其键下的状态命名为传递给combineReducers()

    同样,redux-form reducer 只会修改 state.form,因为它根据其键管理 state.form 状态切片。

    【讨论】:

      【解决方案2】:

      index.js 中的combineReducers 内部,authReducer 被命名为auth,因此状态可以作为state.auth.XXX 访问

      看看https://github.com/gillisd/react-router-v4-redux-auth/blob/master/client/src/reducers/index.js

      【讨论】:

        猜你喜欢
        • 2016-09-27
        • 2021-07-10
        • 2023-03-23
        • 2019-07-28
        • 2018-08-04
        • 1970-01-01
        • 2019-02-17
        • 2020-06-19
        • 2021-01-08
        相关资源
        最近更新 更多