2.5 KiB
2.5 KiB
id | challengeType | forumTopicId | localeTitle |
---|---|---|---|
5a24c314108439a4d403614b | 6 | 301439 | 创建一个 Redux Store |
Description
store
被定义为单个状态对象,这是学习 Redux 时要理解的第一个重要原则:Redux store 是应用程序状态的唯一真实来源。
这也意味着,如果你的应用程序想要更新状态,只能通过 Redux store 执行,单向数据流可以更轻松地对应用程序中的状态进行监测管理。
Instructions
store
是一个保存和管理应用程序状态的state
,你可以使用 Redux 对象中的createStore()
来创建一个 reduxstore
,此方法将reducer
函数作为必需参数,reducer
函数将在后面的挑战中介绍。该函数已在代码编辑器中为你定义,它只需将state
作为参数并返回一个state
即可。
声明一个store
变量并把它分配给createStore()
方法,然后把reducer
作为一个参数传入即可。
注意: 编辑器中的代码使用 ES6 默认参数语法将 state 的值初始化为5
, 如果你不熟悉默认参数,你可以参考 ES6 全部课程,它里面涵盖了这个内容。
Tests
tests:
- text: redux store 应当存在。
testString: assert(typeof store.getState === 'function');
- text: redux store 的 state 的值为 5。
testString: assert(store.getState()=== 5);
Challenge Seed
const reducer = (state = 5) => {
return state;
}
// Redux 方法可以从 Redux 对象获得
// 例如: Redux.createStore()
// 在这里定义一个 store
Solution
const reducer = (state = 5) => {
return state;
}
//Redux 方法可以从 Redux 对象获得
// 例如: Redux.createStore()
// 在这里定义一个 store:
const store = Redux.createStore(reducer);