2018-10-10 18:03:03 -04:00
---
id: 5a24c314108439a4d4036141
2020-12-16 00:37:30 -07:00
title: React 和 Redux 入门
2018-10-10 18:03:03 -04:00
challengeType: 6
2020-09-07 16:11:48 +08:00
forumTopicId: 301430
2018-10-10 18:03:03 -04:00
---
2020-12-16 00:37:30 -07:00
# --description--
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
这一系列挑战介绍的是 Redux 和 React 的配合, 我们先来回顾一下这两种技术的关键原则是什么。React 是提供数据的视图库, 能以高效、可预测的方式渲染视图。Redux 是状态管理框架,可用于简化 APP 应用状态的管理。在 React Redux app 应用中,通常可创建单一的 Redux store 来管理整个应用的状态。React 组件仅订阅 store 中与其角色相关的数据,你可直接从 React 组件中分发 actions 以触发 store 对象的更新。
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
React 组件可以在本地管理自己的状态,但是对于复杂的应用来说,它的状态最好是用 Redux 保存在单一位置, 有特定本地状态的独立组件例外。最后一点是, Redux 没有内置的 React, 需要安装`react-redux` 包,通过这个方式把 Redux 的`state` 和`dispatch` 作为`props` 传给组件。
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
在接下来的挑战中,先要创建一个可输入新文本消息的 React 组件,添加这些消息到数组里,在视图上显示数组。接着,创建 Redux store 和 actions 来管理消息数组的状态。最后,使用`react-redux` 连接 Redux store 和组件,从而将本地状态提取到 Redux store 中。
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
# --instructions--
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
创建`DisplayMessages` 组件, 把构造函数添加到此组件中, 使用含两个属性的状态初始化该组件, 这两个属性为: input( 设置为空字符串) , `messages` (设置为空数组)。
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
# --hints--
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
`DisplayMessages` 组件应渲染空的`div` 元素。
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
```js
assert(
(function () {
const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages));
return mockedComponent.find('div').text() === '';
})()
);
2018-10-10 18:03:03 -04:00
```
2020-12-16 00:37:30 -07:00
`DisplayMessages` 组件的构造函数应调用`super` ,传入`props` 。
2018-10-10 18:03:03 -04:00
```js
2020-12-16 00:37:30 -07:00
(getUserInput) =>
assert(
(function () {
const noWhiteSpace = getUserInput('index').replace(/\s/g, '');
return (
noWhiteSpace.includes('constructor(props)') & &
noWhiteSpace.includes('super(props')
);
})()
);
2018-10-10 18:03:03 -04:00
```
2020-12-16 00:37:30 -07:00
`DisplayMessages` 组件的初始状态应是`{input: "", messages: []}` 。
2020-09-07 16:11:48 +08:00
2018-10-10 18:03:03 -04:00
```js
2020-12-16 00:37:30 -07:00
assert(
(function () {
const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages));
const initialState = mockedComponent.state();
return (
typeof initialState === 'object' & &
initialState.input === '' & &
Array.isArray(initialState.messages) & &
initialState.messages.length === 0
);
})()
);
2018-10-10 18:03:03 -04:00
```
2020-08-13 17:24:35 +02:00
2020-12-16 00:37:30 -07:00
# --solutions--
2020-09-07 16:11:48 +08:00