任务是创建一个reducer函数来处理多个身份验证操作。在化简器中使用JavaScript switch语句来响应不同的动作事件。这是编写Redux减速器的标准模式。 switch语句应切换action.type并返回适当的身份验证状态。
在我看来,有两种方法是相同的。实际上,我认为方法2优于方法1,因为它实际上更新了状态。但是,freecodecamp似乎不这么认为。有人可以告诉我2和有什么区别。
方法1-创建新对象
const defaultState = {
authenticated: false
};
const authReducer = (state = defaultState, action) => {
// change code below this line
switch (action.type) {
case "LOGIN":
return {
authenticated: true
};
case "LOGOUT":
return {
authenticated: false
};
default:
return defaultState;
}
// change code above this line
};
const store = Redux.createStore(authReducer);
const loginUser = () => {
return {
type: "LOGIN"
};
};
const logoutUser = () => {
return {
type: "LOGOUT"
};
};
方法2:更新现有对象
const defaultState = {
authenticated: false
};
const authReducer = (state = defaultState, action) => {
// Change code below this line
switch(action){
case 'loginUser':
state.authenticated = true;
return state;
case 'logoutUser':
state.authenticated = false;
return state;
default:
return state;
}
// Change code above this line
};
const store = Redux.createStore(authReducer);
const loginUser = () => {
return {
type: 'LOGIN'
}
};
const logoutUser = () => {
return {
type: 'LOGOUT'
}
};
我在方法2中收到的错误消息如下