标签:rip code time class cti one imp script cer
dva 是一个基于 react 和 redux 的轻量应用框架,redux步骤繁杂,更容易出错,搭建成本更高。
1.安装dva-cli:确保版本在0.7.0或以上
$ npm install dva-cli -g $ dva -v 0.7.6
2.创建新应用
$ dva new dva-quickstart
3.启动程序
$ cd dva-quickstart $ npm start
4.使用antd框架
$ npm install antd babel-plugin-import --save
编辑 .roadhogrc
,使 babel-plugin-import
(按需加载)插件生效。
"extraBabelPlugins": [ "transform-runtime", ["import", { "libraryName": "antd", "style": "css" }] ],
5.定义路由
新建 route component routes/products.js
,内容如下:
import React from ‘react‘; const Products = (props) => ( <h2>List of Products</h2> ); export default Products;
添加路由信息到路由表,编辑 router.js
:
import products from ‘./routes/products‘; <Route path="/products" component={products} />
然后在浏览器里打开 http://localhost:8000/#/products ,你应该能看到前面定义的 <h2>
标签。
6.编写页面
新建 components/list.js
文件:
import React from ‘react‘; import PropTypes from ‘prop-types‘; import { Table, Popconfirm, Button } from ‘antd‘; const List = ({ onDelete, products }) => { const columns = [{ title: ‘Name‘, dataIndex: ‘name‘, }, { title: ‘Actions‘, render: (text, record) => { return ( <Popconfirm title="Delete?" onConfirm={() => onDelete(record.id)}> <Button>Delete</Button> </Popconfirm> ); }, }]; return ( <Table dataSource={products} columns={columns} /> ); }; List.propTypes = { onDelete: PropTypes.func.isRequired, products: PropTypes.array.isRequired, }; export default List;
7.定义model
新建 model models/products.js
:
import dva from ‘dva‘; export default { namespace: ‘products‘, state: [], reducers: { ‘delete‘(state, { payload: id }) { return state.filter(item => item.id !== id); }, }, };
在 index.js
里载入他:
app.model(require(‘./models/products‘));
8.connect起来
编辑 routes/products.js
,替换为以下内容:
import React from ‘react‘; import { connect } from ‘dva‘; import List from ‘../components/list‘; const Products = ({ dispatch, products }) => { function handleDelete(id) { dispatch({ type: ‘products/delete‘, payload: id, }); } return ( <div> <h2>List of Products</h2> <List onDelete={handleDelete} products={products} /> </div> ); }; // export default Products; export default connect(({ products }) => ({ products, }))(Products);
我们还需要一些初始数据让这个应用 run 起来。编辑 index.js
:
const app = dva({ initialState: { products: [ { name: ‘dva‘, id: 1 }, { name: ‘antd‘, id: 2 }, ], }, });
参考链接:https://ant.design/docs/react/practical-projects-cn
完整项目地址:待定
安装依赖:npm install
启动项目: npm start
浏览器打开:http://localhost:8000/#/
http://localhost:8000/#/products
标签:rip code time class cti one imp script cer
原文地址:http://www.cnblogs.com/yuanyuan0809/p/7171761.html