3.7 KiB
3.7 KiB
id, title, challengeType, isRequired, forumTopicId, localeTitle
id | title | challengeType | isRequired | forumTopicId | localeTitle |
---|---|---|---|---|---|
5a24c314108439a4d4036157 | Write a Counter with Redux | 6 | false | 301453 | 用 Redux 写一个计数器 |
Description
state
不变性的一些细节,但是,这里是对你到目前为止学到的所有内容的回顾。
Instructions
incAction
和decActio
action creator counterReducer()
,INCREMENT
和DECREMENT
action 类型,最后是 Redux store
。一旦完成,你应该能够 dispatch INCREMENT
或DECREMENT
动作来增加或减少store
中保存的状态。开始构建你的第一个 Redux 应用程序吧,祝你好运!
Tests
tests:
- text: 'action creator <code>incAction</code>应返回一个 action 对象 {type:"INCREMENT"}。'
testString: assert(incAction().type ===INCREMENT);
- text: 'action creator <code>decAction</code>应返回一个 action 对象 {type:"DECREMENT"}。'
testString: assert(decAction().type === DECREMENT);
- text: Redux store 应该将<code>state</code>初始化为 0。
testString: assert(store.getState() === 0);
- text: 在 Redux store 上 dispatch <code>incAction</code>应该将<code>state</code>增加 1。
testString: assert((function() { const initialState = store.getState(); store.dispatch(incAction()); const incState = store.getState(); return initialState + 1 === incState })());
- text: 在 Redux store 上 dispatch <code>decAction</code>应该将<code>state</code>减少 1。
testString: assert((function() { const initialState = store.getState(); store.dispatch(decAction()); const decState = store.getState(); return initialState - 1 === decState })());
- text: <code>counterReducer</code>必须是一个函数。
testString: assert(typeof counterReducer === 'function');
Challenge Seed
const INCREMENT = null; // 为增量 action 类型定义一个常量
const DECREMENT = null; // 为减量 action 类型定义一个常量
const counterReducer = null; // 定义计数器,它将根据收到的action增加或减少状态
const incAction = null; // 定义一个用于递增的 action creator
const decAction = null; // 定义一个用于递减的 action creator
const store = null; // 在这里定义一个 Redux store,传递你的 reducer
Solution
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
const counterReducer = (state = 0, action) => {
switch(action.type) {
case INCREMENT:
return state + 1;
case DECREMENT:
return state - 1;
default:
return state;
}
};
const incAction = () => {
return {
type: INCREMENT
}
};
const decAction = () => {
return {
type: DECREMENT
}
};
const store = Redux.createStore(counterReducer);