authenticated
属性的单个的 state 对象。你还需要使用 action creators 创建与用户登录和用户注销相对应的 action,以及 action 对象本身。
reducer
函数来处理多个身份验证操作。可以在reducer
通过使用 JavaScript 的switch
来响应不同的 action 事件。这是编写 Redux reducer 时的标准模式,switch 语句选择action.type
中的一个值并返回相应的身份验证状态。
注意: 此时,不要担心 state 的不变性,因为在这个示例中它很小而且很简单。所以对于每个操作你都可以返回一个新对象,比如{authenticated:true}
。另外,不要忘记在 switch 语句中写一个default
case,返回当前的state
。这是很重要的,因为一旦你的程序有多个 reducer,当一个 action 被 dispatch 时它们都会运行,即使 action 与该 reducer 无关。在这种情况下,你要确保返回当前的state
loginUser
函数应该返回一个 {type:"LOGIN"} 对象。'
testString: assert(loginUser().type === 'LOGIN');
- text: '调用logoutUser
函数应该返回一个 {type:"LOGOUT"} 对象。'
testString: assert(logoutUser().type === 'LOGOUT');
- text: 'store 应该设置一个初始化对象 {authenticated:false}。'
testString: assert(store.getState().authenticated === false);
- text: dispatch loginUser
应该将 store 中的 state 的authenticated
值更新为true
。
testString: assert((function() { const initialState = store.getState(); store.dispatch(loginUser()); const afterLogin = store.getState(); return initialState.authenticated === false && afterLogin.authenticated === true })());
- text: dispatch logoutUser
应该将 store 中的 state 的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 })());
- text: authReducer
函数应该使用switch
语句处理多个 action 类型。
testString: getUserInput => assert( getUserInput('index').toString().includes('switch') && getUserInput('index').toString().includes('case') && getUserInput('index').toString().includes('default'));
```