包含历史和撤销/重做功能的图书搜索应用程序清单 2 显示了图书搜索应用程序的 App 组件的最终实现。
清单 2. 最终的图书搜索应用程序 (containers/app.js)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| import React from 'react';
import ControlsContainer from './controls';
import BooksContainer from './books';
import StateViewerContainer from './stateviewer';
const titleStyle = {
fontFamily: 'tahoma',
fontSize: '24px',
textAlign: 'center'
}
const Title = () => (
<div style={titleStyle}>
Book Search
</div>
);
export default () => (
<div>
<Title />
<hr/>
<ControlsContainer />
<BooksContainer />
<StateViewerContainer />
</div>
)
|
App 组件包含 3 个组件:ControlsContainer、BooksContainer 和 StateViewerContainer。ControlsContainer 包含历史滑块和箭头按钮,StateViewerContainer 包含一个显示当前状态的无状态组件。我首先会介绍 StateViewerContainer。
状态查看器组件清单 3 显示了状态查看器容器:
清单 3. 状态查看器容器 (containers/stateviewer.js)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| import { connect } from 'react-redux';
import StateViewer from '../components/stateviewer';
import stateHistory from '../statehistory';
const mapStateToProps = state => {
return {
books: state.books,
topic: state.topic,
currentStatus: state.currentStatus,
displayMode: state.displayMode,
history: stateHistory
}
}
export default connect(
mapStateToProps,
null
)(StateViewer);
|
stateviewer 容器将 5 个属性映射到它包含的无状态组件。状态查看器无状态组件在清单 4 中使用了这些属性。
清单 4. stateviewer 无状态组件 (components/stateviewer.js)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
| import React from 'react';
const StateViewer = ({
topic,
books,
currentStatus,
displayMode,
history
}) => {
const styles = {
container: {
margin: '20px',
width: '400px',
fontFamily: 'tahoma'
},
title: {
fontSize: '24px',
marginTop: '25px'
},
state: {
marginTop: '10px'
},
hr: {
marginTop: '50px'
}
};
return(
<div style={styles.container}>
<hr style={styles.hr}/>
<div style={styles.title}>
Application State
</div>
<div style={styles.state}>
Topic: {topic}<br/>
Display mode: { displayMode }<br/>
Current status: { currentStatus }<br/>
Books displayed: { books.length }<br/>
Actions processed: { history.past.length + history.future.length + 1 }<br/>
Current action: { history.past.length + 1 }
</div>
</div>
);
}
StateViewer.propTypes = {
books: React.PropTypes.array.isRequired,
currentStatus: React.PropTypes.string.isRequired,
displayMode: React.PropTypes.string.isRequired,
history: React.PropTypes.object.isRequired,
topic: React.PropTypes.string.isRequired,
};
export default StateViewer;
|
清单 4 中的组件很简单;它仅显示自己的属性,这些属性来自包含它的 StateViewerContainer,该容器从当前状态获得它们。
这就是在页面底部显示应用程序状态的状态查看器。接下来我返回到更有趣的控件组件。 |