【发布时间】: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 调度操作
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