gpt4 book ai didi

javascript - 理解 Redux 的 Reducer 存储状态

转载 作者:行者123 更新时间:2023-11-30 11:20:52 25 4
gpt4 key购买 nike

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

最佳答案

因为 combineReducersindex.js .

当您调用 combineReducers 时,您将所有的 reducer 合并为一个用于构建商店的 reducer。但是,您传递给 combineReducers 的每个单独的 reducer 仅管理它的状态切片。因此,由于您要在 key 下传递 authReducer:

auth: authReducer

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

The state produced by combineReducers() namespaces the states of each reducer under their keys as passed to combineReducers()

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

关于javascript - 理解 Redux 的 Reducer 存储状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49869690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com