authenticated
的属性的单个状态对象来表示它。您还需要动作创建者创建与用户登录和用户注销相对应的操作,以及操作对象本身。 reducer
函数以处理多个身份验证操作。在reducer
使用JavaScript switch
语句来响应不同的操作事件。这是编写Redux减速器的标准模式。 switch语句应该切换action.type
并返回适当的身份验证状态。 注意:此时,不要担心状态不变性,因为在这个例子中它很小而且简单。对于每个操作,您可以返回一个新对象 - 例如, {authenticated: true}
。另外,不要忘记在switch语句中写一个返回当前state
的default
大小写。这很重要,因为一旦您的应用程序有多个Reducer,它们都会在执行操作调度时运行,即使操作与该reducer无关。在这种情况下,您需要确保返回当前state
。 loginUser
应该返回一个对象,其type属性设置为字符串LOGIN
。
testString: 'assert(loginUser().type === "LOGIN", "Calling the function loginUser
should return an object with type property set to the string LOGIN
.");'
- text: 调用函数logoutUser
应该返回一个对象,其type属性设置为字符串LOGOUT
。
testString: 'assert(logoutUser().type === "LOGOUT", "Calling the function logoutUser
should return an object with type property set to the string LOGOUT
.");'
- text: 应使用经过authenticated
属性设置为false
的对象初始化存储。
testString: 'assert(store.getState().authenticated === false, "The store should be initialized with an object with an authenticated
property set to false
.");'
- text: 调度loginUser
应该将store状态中的authenticated
属性更新为true
。
testString: 'assert((function() { const initialState = store.getState(); store.dispatch(loginUser()); const afterLogin = store.getState(); return initialState.authenticated === false && afterLogin.authenticated === true })(), "Dispatching loginUser
should update the authenticated
property in the store state to true
.");'
- text: 调度logoutUser
应将store状态中的authenticated
属性更新为false
。
testString: 'assert((function() { store.dispatch(loginUser()); const loggedIn = store.getState(); store.dispatch(logoutUser()); const afterLogout = store.getState(); return loggedIn.authenticated === true && afterLogout.authenticated === false })(), "Dispatching logoutUser
should update the authenticated
property in the store state to false
.");'
- text: authReducer
函数应该使用switch
语句处理多个动作类型。
testString: 'getUserInput => assert( getUserInput("index").toString().includes("switch") && getUserInput("index").toString().includes("case") && getUserInput("index").toString().includes("default"), "The authReducer
function should handle multiple action types with a switch
statement.");'
```