在尝试理解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.auth
。 authReducer
本质上仅控制状态的auth
键-状态键。因此,当authReducer
返回新状态时,它将更新其切片state.auth
,而不仅仅是state
本身。因此,state.auth.authenticated
被更改,而不是state.authenticated
。 documentation中提到了这一点:combineReducers()
产生的状态命名空间在传递给combineReducers()
的键下每个化简器的状态同样,
redux-form
缩减器将仅修改state.form
,因为它根据其键控制state.form
状态片。