上一篇文章是关于从零构建一个webpack项目,基本已经启动成功了,这篇文章将会讲一下在项目中使用目前最流行的React框架
1、引入babel相关
现代前端基本都是以es6为规范进行开发,所以我们项目中也就需要引入es6。es6是需要使用babel进行转换的,浏览器才能识别
1
2 1npm install --save-dev babel-core babel-loader babel-preset-env babel-preset-es2015 babel-preset-stage-0
2
1
2 1npm i --save-dev babel-plugin-import babel-plugin-transform-decorators-legacy babel-plugin-transform-runtime
2
1
2 1npm i --save-dev babel-preset-react babel-preset-react-app
2
这是项目中关于解析es6的babel引入。安装依赖之后,进行配置
在根目录新建一个 .babelrc 用于babel的配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 1
2{
3 "presets": ["es2015", "env", "react", "stage-0"],
4 "plugins": [
5 [
6 "import", {
7 "libraryName": "antd",
8 "libraryDirectory": "es",
9 "style": "css"
10 }
11 ],
12 [
13 "transform-runtime",
14 {
15 "helpers": false,
16 "polyfill": false,
17 "regenerator": true,
18 "moduleName": "babel-runtime"
19 }
20 ],
21 ["transform-decorators-legacy"]
22 ]
23}
24
2、引入react,redux
1
2 1npm i --save-dev react react-dom redux react-redux react-router-dom redux-thunk
2
对于版本方面我们没有特别的要求,所以就直接是最新版的。
3、引入antd
1
2 1npm i --save-dev antd
2
4、添加文件
创建这样的项目结构, 我们依次添加内容。
首先你需要对react,redux有基本的了解,如果没有,建议去学习一下,如果直接构建项目但是又不了解基础知识,其实是学不到什么的。
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 1import React from 'react';
2import ReactDom from 'react-dom';
3import { Provider } from 'react-redux';
4import { createStore, applyMiddleware } from 'redux';
5import thunk from 'redux-thunk';
6import history from './utils/history';
7import storeTree from './store';
8import App from './APP';
9
10const store = createStore(storeTree, applyMiddleware(thunk));
11
12ReactDom.render(
13 <Provider store={store}>
14 <App history={history}/>
15 </Provider>,
16 document.getElementById('app')
17)
18
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 1import React from 'react';
2// import { Router, Route, Switch } from 'react-router-dom';
3import {
4 BrowserRouter as Router,
5 Route,Switch
6 } from 'react-router-dom';
7import PropTypes from 'prop-types';
8import TodoList from './pages/todoList';
9import TodoDetail from './pages/todoDetail';
10
11const App = ((history) => {
12 return (
13 <Router history={history}>
14 <Switch>
15 <Route path="/" exact component={TodoList}></Route>
16 <Route path="/todoList" exact component={TodoList}></Route>
17 <Route path="/todoDetail" exact component={TodoDetail}></Route>
18 </Switch>
19 </Router>
20 )
21});
22App.propTypes = {
23 history: PropTypes.shape({}).isRequired
24};
25export default App;
26
store.js
1
2
3
4
5
6
7
8
9
10
11 1import { combineReducers } from 'redux';
2import todoListReducer from './pages/todoList/reducer';
3import todoDetailReducer from './pages/todoDetail/reducer';
4
5const storeTree = combineReducers({
6 todoListReducer,
7 todoDetailReducer
8});
9
10export default storeTree;
11
utils/history.js
1
2
3
4
5
6 1// import createHistory from 'history/createBrowserHistory';
2import { createBrowserHistory as createHistory } from 'history';
3
4export default createHistory();
5
6
utils/request.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 1export default async function request(url, options) {
2 return requestDataProcess(url, options);
3}
4async function requestDataProcess(url, options) {
5 if (/post/i.test(options.method)) {
6 let { data } = options;
7 let body = null;
8 if (typeof data === 'string') {
9 body = data;
10 } else {
11 body = JSON.stringify(data);
12 }
13 options.body = body;
14 delete options.data;
15 }
16 let headers = {};
17 headers['Content-Type'] = 'application/json';
18 options.headers = headers;
19
20 const result = await fetch(url, options).then(res => res.json());
21 return result;
22}
23
24
pages/todoList/index.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 1import React, { PureComponent } from 'react';
2import { Table, Button } from 'antd';
3import { connect } from 'react-redux';
4import PropTypes from 'prop-types';
5import { getTodoList } from './action';
6
7@connect(
8 state => state,
9 {
10 getTodoList
11 }
12)
13
14class TodoList extends PureComponent {
15 static propTypes = {
16 getTodoList: PropTypes.func.isRequired,
17 todoListReducer: PropTypes.shape({
18 listData: PropTypes.array.isRequired
19 }).isRequired
20 };
21 constructor(props){
22 super(props);
23 }
24 componentDidMount(){
25 this.props.getTodoList();
26 }
27 render() {
28 const columns = [
29 {title:'事件',dataIndex:'item'},
30 {title:'原因',dataIndex:'reson'},
31 {title:'解决办法',dataIndex:'function'},
32 {title:'结果',dataIndex:'result'}
33 ]
34 const data = this.props.todoListReducer.listData;
35 return (
36 <div>
37 <Table
38 rowKey={(record)=>record.id}
39 columns={columns}
40 dataSource={data}
41 />
42 <Button onClick={()=> {this.props.history.push('./todoDetail')}}>跳转详情</Button>
43 </div>
44 )
45 }
46}
47
48export default TodoList;
49
pages/todoList/action.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 1import request from '../../utils/request';
2
3const listData = res => ({
4 type: 'LIST_DATA',
5 payload: res
6});
7
8export const getTodoList = (params, fn) => async (dispatch) => {
9 try {
10 const result = await request('/api/qq/changeData', {
11 method: 'POST',
12 data: params
13 });
14 await dispatch(listData(result.data));
15 fn();
16 } catch (error) {
17
18 }
19}
20
21
pages/todoList/reducer.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 1const initState = {
2 listData: [
3 {id:1, item: 'sss', reson: 'sad', function: 'asdsd', result: 'ewwwqw'},
4 {id:2, item: 'sss', reson: 'sad', function: 'asdsd', result: 'ewwwqw'},
5 {id:3, item: 'sss', reson: 'sad', function: 'asdsd', result: 'ewwwqw'},
6 {id:4, item: 'sss', reson: 'sad', function: 'asdsd', result: 'ewwwqw'}
7 ]
8};
9
10const todoListReducer = (state=initState, action) => {
11 switch (action.type) {
12 case 'LIST_DATA':
13 return {
14 ...state,
15 ...action.payload,
16 listData: action.payload
17 };
18 default:
19 return {
20 ...state
21 };
22 }
23}
24
25export default todoListReducer;
26
pages/todoDetail/index.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 1import React, { PureComponent } from 'react';
2import { Card, Button } from 'antd';
3import { connect } from 'react-redux';
4import PropTypes from 'prop-types';
5import { getTodoDetail } from './action';
6import './index.less';
7
8@connect(
9 state => state,{
10 getTodoDetail
11 }
12)
13
14class TodoDetail extends PureComponent {
15 static propTypes = {
16 getTodoDetail: PropTypes.func.isRequired,
17 todoDetailReducer: PropTypes.shape({
18 info: PropTypes.objectOf.isRequired
19 }).isRequired
20 };
21 constructor(props){
22 super(props)
23 }
24 componentDidMount(){
25 this.props.getTodoDetail();
26 }
27 render() {
28 const { info } = this.props.todoDetailReducer;
29 return (
30 <div>
31 <Card>
32 {info.asd}
33 </Card>
34 <Card className="st">我来显示个数据</Card>
35 <Button onClick={()=> {this.props.history.push('./todoList')}}>那我跳回列表</Button>
36 </div>
37 )
38 }
39}
40
41export default TodoDetail;
42
pages/todoDetail/action.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 1import request from '../../utils/request';
2
3const detailData = res => ({
4 type: 'DETAIL_DATA',
5 payload: res
6});
7
8export const getTodoDetail = (params, fn) => async (dispatch) => {
9 try {
10 const result = await request('/api/qq/changeData', {
11 method: 'POST',
12 data: params
13 });
14 await dispatch(detailData(result.data));
15 fn();
16 } catch (error) {
17
18 }
19}
20
21
pages/todoDeatil/reducer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 1const initState = {
2 info: {
3 asd:'232323123213'
4 }
5};
6
7const todoDetailReducer = (state=initState, action) => {
8 switch (action.type) {
9 case 'DETAIL_DATA':
10 return {
11 ...state,
12 ...action.payload,
13 info: action.payload
14 };
15 default:
16 return {
17 ...state
18 };
19 }
20}
21
22export default todoDetailReducer;
23
5、问题
在引入的过程中很多问题,大多都是babel配置的问题,因为babel7.x版本升级的原因,所以大部分都是在处理这个问题。
dist/index.html中 加入
1
2 1<div id="app"></div>
2
Plugin/Preset files are not allowed to export objects,webpack报错/babel报错的解决方法
最终呈现的页面就是
将会把这个项目上传到github上,需要的同学可以自行下载运行。
目前来说实现了一个基本的react项目,之后会更加完善这个项目,也会持续更新,做一个比较完善的中后台系统。
链接:实践webpack+es6+react+redux+antd构建项目(一) webpack配置
实践webpack+es6+react+redux+antd构建项目(三) 配置proxy代理
实践webpack+es6+react+redux+antd构建项目(四) 区分dev和prod环境
项目github地址
关注我获取更多前端资源和经验分享