Skip to content

Commit 51ff19e

Browse files
author
lewis liu
committed
Published with https://stackedit.io/
1 parent 9f1ab68 commit 51ff19e

File tree

1 file changed

+284
-2
lines changed

1 file changed

+284
-2
lines changed

r2-bs-alert/README.md

Lines changed: 284 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,285 @@
1-
# React Redux Bootstrap Alert Example
21

3-
![](https://raw.githubusercontent.com/lewis617/react-redux-tutorial/master/r2-bs-alert/public/r2-bs-alert.gif)
2+
# 使用 React、Redux 和 Bootstrap 实现Alert
3+
4+
今天,我们来学习使用 React、Redux 和 Bootstrap 实现Alert。
5+
6+
## 例子
7+
8+
这个例子实现了弹出不同类型信息的功能,这些信息默认会在5秒后消失,你也可以手动点击使其消失。如果你在服务端有信息要提示,还可以通过 Redux 的单一数据源传到客户端在渲染页面时显示出来。
9+
10+
11+
源代码:
12+
13+
https://github.com/lewis617/react-redux-tutorial/tree/master/r2-bs-alert
14+
15+
安装:
16+
17+
```sh
18+
npm i
19+
```
20+
21+
开发环境下运行:
22+
23+
```sh
24+
npm start
25+
```
26+
27+
生产环境下构建:
28+
29+
```sh
30+
npm run build
31+
```
32+
33+
测试:
34+
35+
```sh
36+
npm test
37+
```
38+
39+
## 为何使用 Redux ?
40+
41+
React 有自己的局部状态(Local State),可以帮助我们在不同状态下渲染不同的界面。那么实现 Alert 为何要使用 Redux ?众所周知,Alert 通常都是要在程序中全局使用的:
42+
43+
- 用户操作可能会发出 Alert。
44+
- 网络请求等异步事件的处理器(Event Handler)可能会发出 Alert。
45+
- 甚至服务器渲染页面时,也可能会给客户端带来一个Alert(比如,你提交表单出错了,服务器重定向到表单页面,并显示错误提示)。
46+
47+
知道了 Alert 要全局使用,我们再来看 Redux。Redux 有一个全局单一的数据源,这个数据源可以通过 react-redux 连接到程序的任意一个组件。不但如此,更新这个数据源的 action,也可以全局使用:
48+
49+
- 用户操作可以发起 action。
50+
- 网络请求等异步事件的处理器(Event Handler)可能会发起 action。
51+
- 甚至在服务器端也可以发起 action,然后将单一数据源传给客户端继续使用。
52+
53+
Redux 牛逼的设计让处理全局状态变得特别方便,实现 Universal 渲染(有些人喜欢叫SSR,但我觉得不准确)也变得非常容易。这与实现 Alert 的需求非常吻合,因此,本文通过 Redux 来辅助实现 Alert。
54+
从另一个方面来说,一些不在全局使用的组件和功能,一般使用React的局部状态就可以了,切记不要什么功能都用 Redux 实现。
55+
56+
了解了为何要使用 Redux,我们就开始动工吧!
57+
58+
## 快速创建项目
59+
60+
搭建一个 React APP 的成本是很高的,你需要:
61+
62+
- 使用 Webpack 打包。
63+
- 使用 Babel 编译。
64+
- 搭建开发服务器。
65+
- 使用 ESLint 进行语法检查。
66+
- 使用 Mocha 或 Jest 进行测试。
67+
- ……
68+
69+
很多人诟病这一点,不过这些东西都是重复性的体力活,社区早就造好了轮子,来提高生产力。本文就使用了 [create-react-app](https://github.com/facebookincubator/create-react-app) 来快速搭建项目。All you need is these command:
70+
71+
```sh
72+
npm install -g create-react-app
73+
74+
create-react-app my-app
75+
cd my-app/
76+
npm start
77+
```
78+
79+
然后上述所有东西就都有了!
80+
81+
>注意,要将 npm 设为淘宝源或你自己公司的私有 npm 源(只要快就行),否则速度会非常慢,甚至可能导致安装失败。
82+
83+
接下来,我们就开始编写代码。
84+
85+
## 设计编写 Redux
86+
87+
在一个 React 与 Redux 中的程序中,React 负责程序界面,而 Redux 负责程序功能。由于本例界面比较容易,所以我们先来设计 Redux。
88+
89+
我们期望的Alert 的功能包括:
90+
91+
- 显示一条信息。
92+
- 隐藏一条信息。
93+
- 显示一条信息,过几秒自动隐藏。
94+
- 如果服务器传来有信息,在页面渲染完,过几秒也自动隐藏。
95+
96+
功能明确了,让我们把它们写成函数:
97+
98+
- alertShow
99+
- alertHide
100+
- alertMessage
101+
- hideAllAlert
102+
103+
src/alert/redux.js
104+
105+
```js
106+
export const ALERT_SHOW = 'ALERT_SHOW';
107+
export const ALERT_HIDE = 'ALERT_HIDE';
108+
109+
export function alertShow(messageText, messageType, key) {
110+
return {
111+
type: ALERT_SHOW,
112+
payload: {
113+
messageText, messageType, key
114+
}
115+
};
116+
}
117+
118+
export function alertHide(key) {
119+
return {
120+
type: ALERT_HIDE,
121+
payload: { key }
122+
};
123+
}
124+
125+
export function alertMessage(messageText, messageType, delay = 5000) {
126+
return (dispatch, getState) => {
127+
if (typeof messageText === 'string' && ['success', 'warning', 'danger', 'info'].indexOf(messageType) > -1) {
128+
const key = getState().alerts.lastKey + 1;
129+
dispatch(alertShow(messageText, messageType, key));
130+
setTimeout(() => dispatch(alertHide(key)), delay);
131+
} else {
132+
console.error('messageText must be string and messageType must be success, warning, danger, info');
133+
}
134+
};
135+
}
136+
137+
export function hideAllAlert(delay = 5000) {
138+
return (dispatch, getState) => {
139+
getState().alerts.items.forEach((item) => {
140+
setTimeout(() => {
141+
dispatch(alertHide(item.key));
142+
}, delay);
143+
});
144+
};
145+
}
146+
```
147+
尽管部分逻辑有点复杂,但都封装在 action 创建函数中了,多么清晰和模块化!接下来,我们编写 reducer 来根据这些 action,进行 state 的更新。
148+
src/alert/redux.js
149+
150+
export default function (state = { lastKey: -1, items: [] }, action) {
151+
switch (action.type) {
152+
case ALERT_SHOW:
153+
return {
154+
...state,
155+
items: [...state.items, action.payload],
156+
lastKey: state.lastKey + 1
157+
};
158+
case ALERT_HIDE:
159+
return {
160+
...state,
161+
items: state.items.filter(item => (item.key !== action.payload.key))
162+
};
163+
default:
164+
return state;
165+
}
166+
}
167+
这里使用了解构赋值和重写的语法来保证 state 的不可变(Immutable)。
168+
169+
>Redux 的 state 要求是不可变数据,这么做的原因是方便进行快速变更检查,进而有利于React组件判断是否需要重新渲染(re-render)。另外,不可变数据还有利于进行状态回退,错误追踪。不可变数据是函数式编程中一个常用的概念。关于不可变以及函数式编程在 React 与 Redux 中的应用,《React与Redux开发实例精解》这本书中有非常详细的介绍,推荐阅读参考。
170+
171+
至此,Redux的编写就完成了。它的输出有四个:
172+
173+
- reducer函数,用于创建store。
174+
- alertHide 函数用于隐藏指定信息。
175+
- alertMessage 函数用于显示一条信息,并在几秒后隐藏。
176+
- hideAllAlert 函数用于在渲染完页面后,过几秒隐藏服务器传来的信息。
177+
178+
接下来,我们来编写 React 组件。
179+
180+
## 设计编写 React 组件
181+
182+
React 组件的功能包括三个:
183+
184+
- 渲染要显示的信息,并根据类型渲染成不同颜色。
185+
- 为每条信息渲染一个按钮,使用户可以通过点击按钮隐藏该信息。
186+
- 在第一次渲染后,过几秒隐藏来自服务器的信息。
187+
188+
为此,我们做了以下几件事:
189+
190+
- 首先,使用 react-redux 的 connect 将 Redux 的 state 和 action 创建函数传给组件。
191+
- 然后在组件中遍历渲染出所有信息(使用了 react-bootstrap 提供的 Alert 组件)。
192+
- 最后,将 alertHide 函数绑在按钮的点击事件上,将 hideAllAlert 函数绑在组件渲染后的生命周期钩子上。
193+
194+
组件功能就实现了!
195+
196+
```js
197+
src/alert/AlertList.js
198+
199+
import React, { Component, PropTypes } from 'react';
200+
import { connect } from 'react-redux';
201+
import Alert from 'react-bootstrap/lib/Alert';
202+
import { hideAllAlert, alertHide } from './redux';
203+
204+
class AlertList extends Component {
205+
static propTypes = {
206+
alerts: PropTypes.array.isRequired,
207+
hideAllAlert: PropTypes.func.isRequired,
208+
alertHide: PropTypes.func.isRequired
209+
};
210+
211+
componentDidMount() {
212+
this.props.hideAllAlert();
213+
}
214+
215+
render() {
216+
const { alerts, alertHide } = this.props;
217+
return (
218+
<div>
219+
{alerts.map((item, i) => (
220+
<Alert
221+
key={i}
222+
bsStyle={item.messageType}
223+
onDismiss={() => alertHide(item.key)}
224+
>
225+
{item.messageText}
226+
</Alert>
227+
))}
228+
</div>
229+
);
230+
}
231+
}
232+
233+
export default connect(
234+
state => ({
235+
alerts: state.alerts.items
236+
}),
237+
{ hideAllAlert, alertHide }
238+
)(AlertList);
239+
240+
```
241+
242+
为了让 connect 可以获取到 Redux 的 state 和 dispatch 方法,我们还需要在组件顶部提供store。
243+
244+
src/index.js
245+
246+
```js
247+
// 三个参数分别为 reducer、initialState 和 enhancer
248+
const store = createStore(
249+
combineReducers({ alerts: alertsReducer }),
250+
{},
251+
applyMiddleware(thunk)
252+
);
253+
254+
// 在渲染之前发起action,用于模拟从服务器传来的信息
255+
store.dispatch(alertMessage('message from server', 'info'));
256+
257+
ReactDOM.render(
258+
<Provider store={store}>
259+
<App />
260+
</Provider>,
261+
document.getElementById('root')
262+
);
263+
```
264+
265+
为了使用 bootstrap,还需要安装 bootstrap,并引用它的样式文件。
266+
267+
```sh
268+
npm i bootstrap@3 --save
269+
```
270+
271+
src/index.js
272+
273+
```js
274+
import 'bootstrap/dist/css/bootstrap.css';
275+
```
276+
277+
至此,所有功能就都实现了!在后续的文章中,我们将介绍如何测试本例编写的 Redux 函数以及 React 组件。要知道,写测试是一个工程师走向成熟的必经之路,而且在 React 与 Redux 的应用中编写测试简直太方便了!
278+
279+
总结
280+
281+
- Redux 适合实现全局性的组件和功能,一些局部使用的功能使用 React 的局部状态即可。
282+
- 推荐使用 create-react-app 来快速搭建React应用。
283+
- Redux 的 action 创建函数与要实现的功能一一对应。
284+
- Redux 的 state 为不可变数据。
285+
- 使用 react-redux 的 connect 将 Redux 的 state 和 action 创建函数连接到组件,进而渲染界面,绑定事件。

0 commit comments

Comments
 (0)