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