2.6 KiB
2.6 KiB
id | title | challengeType | isRequired | videoUrl | localeTitle |
---|---|---|---|---|---|
5a24c314108439a4d4036145 | Map State to Props | 6 | false | 将状态映射到道具 |
Description
Provider
组件允许您为React组件提供state
和dispatch
,但您必须准确指定所需的状态和操作。这样,您可以确保每个组件只能访问所需的状态。您可以通过创建两个函数来完成此任务: mapStateToProps()
和mapDispatchToProps()
。在这些函数中,您可以声明要访问的状态段以及需要分配的操作创建者。一旦这些功能到位,您将看到如何使用React Redux connect
方法在另一个挑战中将它们连接到您的组件。 注意:在幕后,React Redux使用store.subscribe()
方法实现mapStateToProps()
。 Instructions
mapStateToProps()
。此函数应将state
作为参数,然后返回将该状态映射到特定属性名称的对象。您可以通过props
访问这些属性。由于此示例将应用程序的整个状态保存在单个数组中,因此您可以将整个状态传递给组件。在要返回的对象中创建属性messages
,并将其设置为state
。 Tests
tests:
- text: const <code>state</code>应该是一个空数组。
testString: 'assert(Array.isArray(state) && state.length === 0, "The const <code>state</code> should be an empty array.");'
- text: <code>mapStateToProps</code>应该是一个函数。
testString: 'assert(typeof mapStateToProps === "function", "<code>mapStateToProps</code> should be a function.");'
- text: <code>mapStateToProps</code>应该返回一个对象。
testString: 'assert(typeof mapStateToProps() === "object", "<code>mapStateToProps</code> should return an object.");'
- text: 将数组作为状态传递给<code>mapStateToProps</code>应该返回分配给<code>messages</code>键的数组。
testString: 'assert(mapStateToProps(["messages"]).messages.pop() === "messages", "Passing an array as state to <code>mapStateToProps</code> should return this array assigned to a key of <code>messages</code>.");'
Challenge Seed
const state = [];
// change code below this line
Solution
// solution required