安装 dva-cli
$ npm install dva-cli -g
$ dva -v
dva-cli version 0.9.1
创建新应用
$ dva new dva-quickstart
进入项目
$ cd dva-quickstart
$ npm start
出现以下情形,恭喜你,说明项目成功启动
Compiled successfully!
The app is running at:
http://localhost:8000/
Note that the development build is not optimized.
To create a production build, use npm run build.
这时候你可能需要配合其他UI框架一起使用此处以Antd 为例
$ npm install antd babel-plugin-import --save
编辑 .webpackrc,使 babel-plugin-import 插件生效。
{
+ "extraBabelPlugins": [
+ ["import", { "libraryName": "antd", "libraryDirectory": "es", "style": "css" }]
+ ]
}
定义路由
新建 route 在route下新建文件Products.js
import React from 'react';
const Products = (props) => (
List of Products
);
export default Products;
添加路由信息到路由表,编辑 router.js
+ import Products from './routes/Products';
...
+
编写 UI Component
新建 Component在Component下新建文件Products.js
import React from 'react';
import PropTypes from 'prop-types';
import { Table, Popconfirm, Button } from 'antd';
const ProductList = ({ onDelete, products }) => {
const columns = [{
title: 'Name',
dataIndex: 'name',
}, {
title: 'Actions',
render: (text, record) => {
return (
onDelete(record.id)}>
);
},
}];
return (
);
};
ProductList.propTypes = {
onDelete: PropTypes.func.isRequired,
products: PropTypes.array.isRequired,
};
export default ProductList;
定义 Model
新建 Model在Model下新建文件Products.js
export default {
namespace: 'products',
state: [],
reducers: {
'delete'(state, { payload: id }) {
return state.filter(item => item.id !== id);
},
},
};
这个 model 里:
namespace 表示在全局 state 上的 key
state 是初始值,在这里是空数组
reducers 等同于 redux 里的 reducer,接收 action,同步更新 state
在index.js里面载入
// 3. Model
+ app.model(require('./models/products').default);
connect 起来
我们已经完成了model 和component
这里的connect类似于redux里面的connect
重新编辑route下的Product.js
import React from 'react';
import { connect } from 'dva';
import ProductList from '../components/ProductList';
const Products = ({ dispatch, products }) => {
function handleDelete(id) {
dispatch({
type: 'products/delete',
payload: id,
});
}
return (
List of Products
);
};
// export default Products;
export default connect(({ products }) => ({
products,
}))(Products);
最后,我们还需要一些初始数据让这个应用 run 起来。编辑 index.js:
- const app = dva();
+ const app = dva({
+ initialState: {
+ products: [
+ { name: 'dva', id: 1 },
+ { name: 'antd', id: 2 },
+ ],
+ },
+ });
此时刷新页面就能看到相应效果
构建应用
完成开发并且在开发环境验证之后,就需要部署给我们的用户了。先执行下面的命令:
$ npm run build
等待一段时间
> @ build /private/tmp/myapp
> roadhog build
Creating an optimized production build...
Compiled successfully.
File sizes after gzip:
82.98 KB dist/index.js
270 B dist/index.css
build 命令会打包所有的资源,包含 JavaScript, CSS, web fonts, images, html 等。然后你可以在 dist/ 目录下找到这些文件。
参考官方地址:https://dvajs.com/guide/getting-started.html