概念
// http://localhost:3000/
//models
import IndexPage from './routes/IndexPage';
import Products from './routes/Products';
//Router Component
function RouterConfig({ history }) {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={IndexPage} />
<Route path="/products" exact component={Products} />
</Switch>
</Router>
);
}
//Router Component dispatch
const Products = ({ dispatch, products }) => {
function handleDelete(id) {
dispatch({
type: 'products/delete',
payload: id,
});
}
return (
<div>
<h2>List of Products</h2>
<ProductList onDelete={handleDelete} products={products} />
</div>
);
};
connect(({ products }) => ({
products,
}))(Products);
//models
export default {
namespace: 'products',
state: [],
reducers: {
'delete'(state, { payload: id }) {
return state.filter(item => item.id !== id);
},
},
};
//通过dva实现整个流程
const app = dva({
initialState: {
products: [
{ name: 'dva', id: 1 },
{ name: 'antd', id: 2 },
],
},
});
// 2. Plugins
//app.use({});
// 3. Model
app.model(require('./models/products').default);
// 4. Router
app.router(require('./router').default);
// 5. Start
app.start('#root');
dva最简结构
umi 和 dva、roadhog 是什么关系?
简单来说,
roadhog 是基于 webpack 的封装工具,目的是简化 webpack 的配置
umi 可以简单地理解为 roadhog + 路由,思路类似 next.js/nuxt.js,辅以一套插件机制,目的是通过框架的方式简化 React 开发
dva 目前是纯粹的数据流,和 umi 以及 roadhog 之间并没有相互的依赖关系,可以分开使用也可以一起使用,个人觉得 umi + dva 是比较搭的
// 创建应用
const app = dva();
// 注册 Model
app.model({
namespace: 'count',
state: 0,
reducers: {
add(state) { return state + 1 },
},
effects: {
*addAfter1Second(action, { call, put }) {
yield call(delay, 1000);
yield put({ type: 'add' });
},
},
});
// 注册视图
app.router(() => <ConnectedApp />);
// 启动应用
app.start('#root');
Umi 与 Dva
├── app.js //配置dva
├── assets
│ └── yay.jpg
├── global.css
├── layouts
│ ├── __tests__
│ │ └── index.test.js
│ ├── index.css
│ └── index.js
└── pages //页面即路由
├── $post
│ ├── comments.js
│ └── index.js
├── 404.js
├── __tests__
│ └── index.test.js
├── document.ejs
├── index.css
├── index.js
├── products // /products
│ ├── index.js //接收products
│ └── model.js //配置 /products的路由
└── users
└── $id$.js
//products/index.js 派发action
const ProductList = ({ 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}
rowKey={record => record.id}
/>
);
};
//接收initialState与dispatch
export default connect(({ products }) => ({
products
}),(dispatch) => {
return {
onDelete: function handleDelete(id) {
dispatch({
type: 'products/delete',
payload: id,
});
}
}
})(ProductList)
//app.js配置dva
export const dva = {
config: {
onError(e) {
e.preventDefault();
console.error(e.message);
},
initialState: {
products: [
{ name: 'dva', id: 1 },
{ name: 'antd', id: 2 },
],
}
},
plugins: [
require('dva-logger')(),
],
};