Skip to content

Commit 539a5aa

Browse files
committed
refactor with react hooks
1 parent be2959f commit 539a5aa

2 files changed

Lines changed: 152 additions & 105 deletions

File tree

Lines changed: 45 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,59 @@
1-
import React from 'react';
1+
import React, {useEffect, useReducer} from 'react';
22
import AppModel from '../models/AppModel';
33
import CopybookModel from '../models/CopybookModel';
44
import Copybook from '../components/Copybook';
55

6-
export default class CopybookContainer extends React.Component {
7-
state = {
8-
copybookRequesting: false,
9-
copybookVisible: CopybookModel.visible,
10-
copybookFileList: CopybookModel.fileList,
11-
copybookSelectedFile: CopybookModel.selectedFile,
12-
copybookFileContent: CopybookModel.fileContent,
6+
const actionTypes = {
7+
UPDATE: 'update',
8+
};
9+
10+
const initState = {
11+
copybookRequesting: false,
12+
copybookVisible: CopybookModel.visible,
13+
copybookFileList: CopybookModel.fileList,
14+
copybookSelectedFile: CopybookModel.selectedFile,
15+
copybookFileContent: CopybookModel.fileContent,
16+
};
17+
18+
function reducer(state, action) {
19+
switch (action.type) {
20+
case actionTypes.UPDATE:
21+
return {
22+
...state,
23+
...action.payload
24+
};
25+
default:
26+
return state;
1327
}
28+
}
1429

15-
constructor(props) {
16-
super(props);
17-
CopybookModel.onUpdated(this.handleCopybookModelUpdate);
30+
export default function CopybookContainer(props) {
31+
const [state, dispatch] = useReducer(reducer, initState);
32+
33+
useEffect(() => {
34+
CopybookModel.onUpdated(handleCopybookModelUpdate);
35+
return () => CopybookModel.offUpdated(handleCopybookModelUpdate);
36+
});
37+
38+
function setState(payload) {
39+
dispatch({type: actionTypes.UPDATE, payload: payload});
1840
}
1941

20-
handleCopybookModelUpdate = (curr, prev, mutation) => {
42+
function handleCopybookModelUpdate(curr, prev, mutation) {
2143
if (mutation.fileList) {
22-
this.setState({
44+
setState({
2345
copybookFileList: CopybookModel.fileList
2446
});
2547
}
2648
if (mutation.fileContent) {
27-
this.setState({
49+
setState({
2850
copybookRequesting: false,
2951
copybookSelectedFile: CopybookModel.selectedFile,
3052
copybookFileContent: CopybookModel.fileContent,
3153
});
3254
}
3355
if (mutation.visible) {
34-
this.setState({
56+
setState({
3557
copybookVisible: CopybookModel.visible,
3658
});
3759
if (CopybookModel.visible) {
@@ -40,20 +62,18 @@ export default class CopybookContainer extends React.Component {
4062
}
4163
}
4264

43-
handleCloseCopybook = () => {
44-
CopybookModel.update({ visible: false });
65+
function handleCloseCopybook() {
66+
CopybookModel.update({visible: false});
4567
}
4668

47-
handleRequestCopybookFile = file => {
48-
this.setState({ copybookRequesting: true });
69+
function handleRequestCopybookFile(file) {
70+
setState({copybookRequesting: true});
4971
CopybookModel.requestRepoFile(file);
5072
AppModel.analytics('copybook&q=read');
5173
}
5274

53-
render() {
54-
return <Copybook {...this.state}
55-
className='copybook-container fix-modal'
56-
onRequestCopybookFile={this.handleRequestCopybookFile}
57-
onCloseCopybook={this.handleCloseCopybook}/>;
58-
}
75+
return <Copybook {...state}
76+
className='copybook-container fix-modal'
77+
onRequestCopybookFile={handleRequestCopybookFile}
78+
onCloseCopybook={handleCloseCopybook}/>;
5979
}

‎src/containers/MainContainer.js‎

Lines changed: 107 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React from 'react';
1+
import React, {useEffect, useReducer} from 'react';
22
import {Container} from 'semantic-ui-react';
33
import SearchBar from '../components/SearchBar';
44
import TitleLogo from '../components/TitleLogo';
@@ -13,90 +13,113 @@ import SourceCode from '../components/SourceCode';
1313
import AppModel from '../models/AppModel';
1414
import DDMSModel from '../models/DDMSModel';
1515

16-
export default class MainContainer extends React.Component {
17-
state = {
18-
isZH: false,
19-
isError: false,
20-
variableRequesting: false,
21-
searchValue: SearchCodeModel.searchValue,
22-
searchLang: SearchCodeModel.searchLang,
23-
page: SearchCodeModel.page,
24-
variableList: SearchCodeModel.variableList,
25-
suggestion: SearchCodeModel.suggestion,
26-
sourceCodeRequesting: false,
27-
sourceCodeVisible: false,
28-
sourceCodeVariable: null,
29-
sourceCodeRepo: null,
16+
const actionTypes = {
17+
UPDATE: 'update',
18+
};
19+
20+
const initState = {
21+
isZH: false,
22+
isError: false,
23+
variableRequesting: false,
24+
searchValue: SearchCodeModel.searchValue,
25+
searchLang: SearchCodeModel.searchLang,
26+
page: SearchCodeModel.page,
27+
variableList: SearchCodeModel.variableList,
28+
suggestion: SearchCodeModel.suggestion,
29+
sourceCodeRequesting: false,
30+
sourceCodeVisible: false,
31+
sourceCodeVariable: null,
32+
sourceCodeRepo: null,
33+
};
34+
35+
function reducer(state, action) {
36+
switch (action.type) {
37+
case actionTypes.UPDATE:
38+
return {
39+
...state,
40+
...action.payload
41+
};
42+
default:
43+
return state;
3044
}
45+
}
46+
3147

32-
repoList = null;
48+
export default function MainContainer(props) {
49+
const [state, dispatch] = useReducer(reducer, initState);
3350

34-
constructor(props) {
35-
super(props);
36-
SearchCodeModel.onUpdated(this.handleSearchCodeModelUpdate);
37-
window.addEventListener('hashchange', this.handleLocationHashChanged, false);
51+
useEffect(() => {
3852
AppModel.analytics();
39-
}
53+
setTimeout(handleLocationHashChanged, 100);
54+
window.addEventListener('hashchange', handleLocationHashChanged, false);
55+
return () => window.removeEventListener('hashchange', handleLocationHashChanged);
56+
}, []);
4057

41-
componentDidUpdate(prevProps) {
42-
this.state.variableList.length && document.body.classList.add('dark');
43-
}
58+
useEffect(() => {
59+
state.variableList.length && document.body.classList.add('dark');
60+
}, [state.variableList]);
61+
62+
useEffect(() => {
63+
SearchCodeModel.onUpdated(handleSearchCodeModelUpdate);
64+
return () => SearchCodeModel.offUpdated(handleSearchCodeModelUpdate);
65+
});
4466

45-
componentDidMount() {
46-
this.handleLocationHashChanged();
67+
function setState(payload) {
68+
dispatch({type: actionTypes.UPDATE, payload: payload});
4769
}
4870

49-
checkError(data) {
50-
if (this.state.variableRequesting) {
71+
72+
function checkError(data) {
73+
if (state.variableRequesting) {
5174
// no search result
52-
if (data.variableList.length < 1 || data.variableList[data.variableList.length - 1].length < 1) {
75+
if (data.variableList.length < 1 || data.variableList[data.variableList.length - 1].length < 1) {
5376
return true;
5477
}
5578
}
5679
return false;
5780
}
5881

59-
requestVariable = (val, lang) => {
60-
const langChanged = lang ? (lang.join(',') != this.state.searchLang.join(',')) : !!this.state.searchLang;
82+
function requestVariable(val, lang) {
83+
const langChanged = lang ? (lang.join(',') != state.searchLang.join(',')) : !!state.searchLang;
6184
val = decodeURIComponent(val);
62-
let page = this.state.page;
63-
if (val == this.state.searchValue && !langChanged) {
85+
let page = state.page;
86+
if (val == state.searchValue && !langChanged) {
6487
page += 1;
6588
} else {
6689
page = 0;
6790
}
68-
this.setState({searchValue: val, variableRequesting: true});
69-
SearchCodeModel.requestVariable(val, page, lang || this.state.searchLang);
91+
setState({searchValue: val, variableRequesting: true});
92+
SearchCodeModel.requestVariable(val, page, lang || state.searchLang);
7093
AppModel.analytics('q=' + val);
7194
DDMSModel.postKeyWords(val);
72-
this.updateDocTitle(val);
95+
updateDocTitle(val);
7396
}
7497

75-
requestSourceCode = repo => {
76-
this.setState({
98+
function requestSourceCode(repo) {
99+
setState({
77100
sourceCodeVisible: true,
78101
sourceCodeRequesting: true,
79102
sourceCodeRepo: repo
80103
});
81104
SearchCodeModel.requestSourceCode(repo.id);
82-
AppModel.analytics('sourcecode&q=' + this.state.sourceCodeVariable.keyword);
105+
AppModel.analytics('sourcecode&q=' + state.sourceCodeVariable.keyword);
83106
}
84107

85-
updateDocTitle = title => {
86-
document.title = `${title? (title + ' - ') : ''}CODELF`;
108+
function updateDocTitle(title) {
109+
document.title = `${title ? (title + ' - ') : ''}CODELF`;
87110
}
88111

89-
handleLocationHashChanged = e => {
112+
function handleLocationHashChanged(e) {
90113
e && e.preventDefault();
91114
const hash = HashHandler.get();
92-
hash && this.requestVariable(hash.replace(/(\?.*)/, ''));
115+
hash && requestVariable(hash.replace(/(\?.*)/, ''));
93116
}
94117

95-
handleSearchCodeModelUpdate = (curr, prev, mutation) => {
118+
function handleSearchCodeModelUpdate(curr, prev, mutation) {
96119
if (mutation.variableList) {
97-
this.setState({
98-
isZH: SearchCodeModel.isZH || this.state.isZH,
99-
isError: this.checkError(curr),
120+
setState({
121+
isZH: SearchCodeModel.isZH || state.isZH,
122+
isError: checkError(curr),
100123
variableRequesting: !mutation.variableList,
101124
searchValue: SearchCodeModel.searchValue,
102125
searchLang: SearchCodeModel.searchLang,
@@ -106,57 +129,61 @@ export default class MainContainer extends React.Component {
106129
});
107130
}
108131
if (mutation.sourceCode) {
109-
this.setState({
132+
setState({
110133
sourceCodeRequesting: false,
111134
sourceCode: SearchCodeModel.sourceCode
112135
});
113136
}
114137
}
115138

116-
handleSearch = (val, lang) => {
117-
if (val === null || val === undefined || this.state.variableRequesting) { return; }
139+
function handleSearch(val, lang) {
140+
if (val === null || val === undefined || state.variableRequesting) {
141+
return;
142+
}
118143
val = val.trim().replace(/\s+/ig, ' '); // filter spaces
119-
if (val.length < 1) { return; }
120-
if (val == this.state.searchValue) {
121-
this.requestVariable(val, lang);
122-
} else {
123-
this.setState({searchLang: lang});
144+
if (val.length < 1) {
145+
return;
146+
}
147+
if (val == state.searchValue) {
148+
requestVariable(val, lang);
149+
} else {
150+
setState({searchLang: lang});
124151
setTimeout(() => HashHandler.set(val)); // update window.location.hash
125152
}
126153
}
127154

128-
handleOpenSourceCode = variable => {
129-
this.setState({sourceCodeVariable: variable});
130-
setTimeout(() => this.requestSourceCode(variable.repoList[0]), 0);
155+
function handleOpenSourceCode(variable) {
156+
setState({sourceCodeVariable: variable});
157+
setTimeout(() => requestSourceCode(variable.repoList[0]), 0);
131158
}
132159

133-
handleCloseSourceCode = () => {
134-
this.setState({sourceCodeVisible: false});
160+
function handleCloseSourceCode() {
161+
setState({sourceCodeVisible: false});
135162
}
136163

137-
handleRequestSourceCode = repo => {
138-
this.requestSourceCode(repo);
164+
function handleRequestSourceCode(repo) {
165+
requestSourceCode(repo);
139166
}
140167

141-
renderSloganImage() {
142-
if (this.state.page > 0 || this.state.variableList.length) { return ''; }
168+
function renderSloganImage() {
169+
if (state.page > 0 || state.variableList.length) {
170+
return '';
171+
}
143172
return <div className='slogan-image'><img src='images/twohardtings.jpg'/></div>;
144173
}
145174

146-
render() {
147-
return (
148-
<Container className='main-container'>
149-
<TitleLogo/>
150-
<SearchBar placeholder='AI 人工智能' {...this.state} onSearch={this.handleSearch}/>
151-
<Suggestion {...this.state}/>
152-
{this.state.variableRequesting ? <Loading/> : (this.state.isError ? <SearchError/> : '')}
153-
{this.renderSloganImage()}
154-
<VariableList {...this.state} onOpenSourceCode={this.handleOpenSourceCode}/>
155-
{this.state.variableList.length ? <Donate {...this.state}/> : ''}
156-
<SourceCode {...this.state}
157-
onRequestSourceCode={this.handleRequestSourceCode}
158-
onCloseSourceCode={this.handleCloseSourceCode}/>
159-
</Container>
160-
)
161-
}
175+
return (
176+
<Container className='main-container'>
177+
<TitleLogo/>
178+
<SearchBar placeholder='AI 人工智能' {...state} onSearch={handleSearch}/>
179+
<Suggestion {...state}/>
180+
{state.variableRequesting ? <Loading/> : (state.isError ? <SearchError/> : '')}
181+
{renderSloganImage()}
182+
<VariableList {...state} onOpenSourceCode={handleOpenSourceCode}/>
183+
{state.variableList.length ? <Donate {...state}/> : ''}
184+
<SourceCode {...state}
185+
onRequestSourceCode={handleRequestSourceCode}
186+
onCloseSourceCode={handleCloseSourceCode}/>
187+
</Container>
188+
)
162189
}

0 commit comments

Comments
 (0)