ant-design/docs/react/practical-projects.en-US.md

279 lines
7.5 KiB
Markdown
Raw Normal View History

2016-09-18 17:39:11 +08:00
---
order: 3
2016-12-28 15:45:37 +08:00
title: Real project with dva
2016-09-18 17:39:11 +08:00
---
[dva](https://github.com/dvajs/dva) is a React and redux based, lightweight and elm-style framework, which supports side effects, hot module replacement, dynamic on demand, react-native, and SSR. It has been widely used in production environments.
2016-09-18 17:39:11 +08:00
This article will guide you to create a simple application from zero using dva and antd.
Include the following:
---
## Install dva-cli
2016-09-18 17:39:11 +08:00
Install dva-cli with npm, and make sure the version is later than `0.8.1`.
2016-09-18 17:39:11 +08:00
```bash
$ npm install dva-cli -g
$ dva -v
0.8.1
2016-09-18 17:39:11 +08:00
```
## Create New App
After you have installed dva-cli, you can have access to the `dva` command in terminal ([can't access?](http://stackoverflow.com/questions/15054388/global-node-modules-not-installing-correctly-command-not-found)). Now, create a new application with `dva new`.
2016-09-18 17:39:11 +08:00
```bash
$ dva new dva-quickstart
```
This creates a `dva-quickstart` directory, that contains the project directories and files, and provides a development server, build script, mock service, proxy server and so on.
2016-09-18 17:39:11 +08:00
Then `cd` to the `dva-quickstart` directory, and start the development server.
2016-09-18 17:39:11 +08:00
```bash
$ cd dva-quickstart
$ npm start
```
2016-11-16 21:34:28 +08:00
After a few seconds, you will see the following output:
2016-09-18 17:39:11 +08:00
```bash
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.
2016-09-18 17:39:11 +08:00
```
Open http://localhost:8000 in your browser, you will see the dva welcome page.
2016-09-18 17:39:11 +08:00
## Integrate antd
Install `antd` and `babel-plugin-import` with npm. `babel-plugin-import` is used to automatically import scripts and stylesheets from antd on demand. See [repo](https://github.com/ant-design/babel-plugin-import) 。
2016-09-18 17:39:11 +08:00
```bash
$ npm install antd babel-plugin-import --save
2016-09-18 17:39:11 +08:00
```
Edit `.roadhogrc` to integrate `babel-plugin-import`.
2016-09-18 17:39:11 +08:00
```diff
"extraBabelPlugins": [
- "transform-runtime"
+ "transform-runtime",
2017-11-29 20:27:52 +08:00
+ ["import", { "libraryName": "antd", "libraryDirectory": "es", "style": "css" }]
],
2016-09-18 17:39:11 +08:00
```
> Notice: dva-cli's build and server is based on roadhog, view [roadhog#Configuration](https://github.com/sorrycc/roadhog/blob/master/README_en-us.md#configuration) for more `.roadhogrc` Configuration.
2016-09-18 17:39:11 +08:00
## Define Router
We need to write an application displaying the list of products. The first step is to create a route.
Create a route component `routes/Products.js`:
```javascript
import React from 'react';
2016-11-14 14:16:12 +08:00
const Products = (props) => (
<h2>List of Products</h2>
);
2016-09-18 17:39:11 +08:00
2016-09-19 21:53:00 +08:00
export default Products;
2016-09-18 17:39:11 +08:00
```
2016-11-16 21:34:28 +08:00
Add routing information to router, edit `router.js`:
2016-09-18 17:39:11 +08:00
```diff
+ import Products from './routes/Products';
...
+ <Route path="/products" exact component={Products} />
2016-09-18 17:39:11 +08:00
```
Then open http://localhost:8000/#/products in your browser, you should be able to see the `<h2>` tag defined before.
2016-09-18 17:39:11 +08:00
## Write UI Components
As your application grows and you notice you are sharing UI elements between multiple pages (or using them multiple times on the same page), in dva it's called reusable components.
Let's create a `ProductList` component that we can use in multiple places to show a list of products.
Create `components/ProductList.js` by typing:
2016-09-18 17:39:11 +08:00
```javascript
import React from 'react';
import PropTypes from 'prop-types';
2016-09-18 17:39:11 +08:00
import { Table, Popconfirm, Button } from 'antd';
const ProductList = ({ onDelete, products }) => {
2016-11-14 14:16:12 +08:00
const columns = [{
title: 'Name',
dataIndex: 'name',
}, {
title: 'Actions',
render: (text, record) => {
return (
<Popconfirm title="Delete?" onConfirm={() => onDelete(record.id)}>
<Button>Delete</Button>
</Popconfirm>
);
2016-09-18 17:39:11 +08:00
},
2016-11-14 14:16:12 +08:00
}];
2016-09-18 17:39:11 +08:00
return (
<Table
dataSource={products}
columns={columns}
/>
);
};
ProductList.proptypes = {
onDelete: PropTypes.func.isRequired,
products: PropTypes.array.isRequired,
};
export default ProductList;
```
## Define Model
After completing the UI, we will begin processing the data and logic.
2016-09-18 17:39:11 +08:00
dva manages the domain model with `model`, with reducers for synchronous state updates, effects for async logic, and subscriptions for data source subscribe.
2016-09-18 17:39:11 +08:00
Let's create a model `models/products.js` by typing:
2016-09-18 17:39:11 +08:00
```javascript
import dva from 'dva';
export default {
namespace: 'products',
state: [],
reducers: {
'delete'(state, { payload: id }) {
return state.filter(item => item.id !== id);
},
},
};
```
In this model:
- `namespace` represents the key on global state
- `state` is the initial value, here it is an empty array
- `reducers` is equivalent to a reducer in redux, accepting an action, and update state simultaneously
2016-09-18 17:39:11 +08:00
Then don't forget to require it in `index.js`:
```diff
// 3. Model
+ app.model(require('./models/products'));
```
## Connect
So far, we have completed a separate model and component. How do we connect them together?
2016-09-18 17:39:11 +08:00
2016-11-16 21:34:28 +08:00
dva provides a `connect` method. If you are familiar with redux, this `connect` is from react-router.
2016-09-18 17:39:11 +08:00
Edit `routes/Products.js` and replace it with the following:
2016-09-18 17:39:11 +08:00
```javascript
import React from 'react';
import { connect } from 'dva';
import ProductList from '../components/ProductList';
2016-11-14 14:16:12 +08:00
const Products = ({ dispatch, products }) => {
2016-09-18 17:39:11 +08:00
function handleDelete(id) {
2016-11-14 14:16:12 +08:00
dispatch({
2016-09-18 17:39:11 +08:00
type: 'products/delete',
payload: id,
});
}
return (
<div>
<h2>List of Products</h2>
2016-11-14 14:16:12 +08:00
<ProductList onDelete={handleDelete} products={products} />
2016-09-18 17:39:11 +08:00
</div>
);
};
// export default Products;
export default connect(({ products }) => ({
2016-11-14 14:16:12 +08:00
products,
2016-09-18 17:39:11 +08:00
}))(Products);
```
Finally, we need some initial data to make the application run together. Edit `index.js`:
```diff
- const app = dva();
+ const app = dva({
+ initialState: {
+ products: [
+ { name: 'dva', id: 1 },
+ { name: 'antd', id: 2 },
+ ],
+ },
+ });
```
Refresh your browser, you should see the following result:
2016-09-21 11:28:38 +08:00
<p style="text-align: center">
2016-09-18 17:39:11 +08:00
<img src="https://zos.alipayobjects.com/rmsportal/GQJeDDeUCSTRMMg.gif" />
</p>
## Build
Now that we've written our application and verified that it works in development, it's time to get it ready for deployment to our users. To do so, run the following command:
2016-09-18 17:39:11 +08:00
```bash
$ npm run build
```
After a few seconds, the output should be as follows:
```bash
> @ 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
2016-09-18 17:39:11 +08:00
```
The `build` command packages up all of the assets that make up your application —— JavaScript, templates, CSS, web fonts, images, and more. Then you can find these files in the `dist /` directory.
## What's Next
We have completed a simple application, but you may still have lots of questions, such as:
- How to deal with async logic
2016-09-18 17:39:11 +08:00
- How to load initial data elegantly
- How to handle onError globally and locally
- How to load Routes and Models on demand
- How to implement HMR
- How to mock data
- and so on...
You can:
2016-11-16 21:34:28 +08:00
- Visit [dva official website](https://github.com/dvajs/dva).
- Be familiar with the [8 Concepts](https://github.com/dvajs/dva/blob/master/docs/Concepts.md), and understand how they are connected together
- Know all [dva APIs](https://github.com/dvajs/dva/blob/master/docs/API.md)
- Checkout [dva knowledgemap](https://github.com/dvajs/dva-knowledgemap), including all the basic knowledge with ES6, React, dva
- Checkout [more FAQ](https://github.com/dvajs/dva/issues?q=is%3Aissue+is%3Aclosed+label%3Afaq)
- If your project is created with [dva-cli](https://github.com/dvajs/dva-cli) , checkout how to [Configure it](https://github.com/sorrycc/roadhog#配置)