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
完整項目git地址:git clone https://github.com/zyy0816/dva-react-antd.git
拉取后啟動項目三步驟:
1.安裝依賴:npm install
2.啟動項目: npm start
3.瀏覽器打開:http://localhost:8000/#/
http://localhost:8000/#/products
