npm install dva-cli -g
css
2.建立應用react
dva new dvadashboard ajax
[dvadashboard爲項目名]npm
const fs=require('fs'); const path=require('path'); const mockPath=path.join(__dirname+'/mock'); const mock={}; fs.readdirSync(mockPath).forEach(file=>{ Object.assign(mock,require('./mock/'+file)); }); module.exports=mock;複製代碼
mock文件夾下新建user.jsjson
API設置:redux
這裏只模擬倆個api 1.獲取全部用戶數據 2.添加用戶api
const Mock=require('mockjs'); let db=Mock.mock({ 'data|3-6':[{ id:'@id', name:'@name', 'age|18-32':1 }] }); module.exports={ [`GET /api/users`](req,res){ res.status(200).json(db); }, [`POST /api/users`](req,res){ let user=req.body; console.log(req); user.id=Mock.mock('@id'); db.data.push(user); res.status(200).json(user); } }複製代碼
接下來看一下api能不能使用, 進入項目目錄, 執行 npm start 啓動 babel
進入默認頁面 默認端口號 8000 以下是項目啓動後默認頁面markdown
訪問下api http://localhost:8000/api/users 好了,能夠訪問 成功返回模擬用戶列表數據antd
npm install antd babel-plugin-import --save
安裝完成後,配置使用antd 修改.roadhogrc文件
添加 ["import",{ "libraryName":"antd","style":"css" }] 最後文件以下所示:
{ "entry": "src/index.js", "env": { "development": { "extraBabelPlugins": [ "dva-hmr", "transform-runtime", ["import",{ "libraryName":"antd","style":"css" }] ] }, "production": { "extraBabelPlugins": [ "transform-runtime", ["import",{ "libraryName":"antd","style":"css" }] ] } } }複製代碼
這多是最簡單的一個頁面了
import { connect } from 'dva'; const UserPage=()=>{ return ( <div> <h1>UserPage</h1> </div> ); }; export default connect()(UserPage);複製代碼
順手加了個組件動態加載
import React from 'react'; import { Router, Route, Switch } from 'dva/router'; import dynamic from 'dva/dynamic'; import IndexPage from './routes/IndexPage'; function RouterConfig({ history,app }) { const UserPage=dynamic({ app, component:()=>import('./routes/usersPage') }); return ( <Router history={history}> <Switch> <Route path="/" exact component={IndexPage} /> <Route path="/users" exact component={UserPage} /> </Switch> </Router> ); } export default RouterConfig;複製代碼
查看一下路由配置效果 訪問http://localhost:8000/#/users
顯示內容了
import fetch from 'dva/fetch'; const checkStatus=(response)=>{ if(response.status>=200 && response.status<=200){ return response; } const error=new Error(response.statusText); error.response=response; throw error; }; export default async function request(url,options={}) { options.headers={ 'Content-Type':'application/json' } const response=await fetch(url,options); checkStatus(response); const data=await response.json(); return data; }複製代碼
這裏爲了理解簡單 省略一層 user.service (封裝基礎ajax通信 提供業務接口) 在業務層中直接調用request裏方法 【只是爲了學習方便】
import request from '../utils/request'; const User={ namespace:"user", state:{ list:[], visibleModal:false }, reducers:{ save(state,{ payload:{ data:list } }){ return { ...state, list }; } }, effects:{ * query({},{ call,put }){ const { data }=yield call(request,'/api/users',{ method:'GET' }); yield put({type:'save',payload:{ data }}); }, * create({ payload:{ user } },{ call,put }){ yield call(request,'/api/users',{ body:JSON.stringify(user), method:'POST' }); yield put({type:'query',payload:{ }}); } }, subscriptions:{ setup({ dispatch,history }){ console.log('running subscriptions ...'); return history.listen(({ pathname,search })=>{ console.log(`pathname: ${pathname}`); dispatch({ type:'query'}); }); } } }; export default User;複製代碼
import React from 'react'; import { Router, Route, Switch } from 'dva/router'; import dynamic from 'dva/dynamic'; import IndexPage from './routes/IndexPage'; function RouterConfig({ history,app }) { const UserPage=dynamic({ app, models:()=>[ import('./models/user') ], component:()=>import('./routes/usersPage') }); return ( <Router history={history}> <Switch> <Route path="/" exact component={IndexPage} /> <Route path="/users" exact component={UserPage} /> </Switch> </Router> ); } export default RouterConfig;複製代碼
順手也把添加用戶的表單建了吧
user.js
import { Table,Button } from 'antd'; import { connect } from 'dva'; import UserModal from './create'; const UserTable = ({ list,dispatch }) => { const createUser=(user)=>{ dispatch({ type:'user/create', payload:{ user } }); }; const columns=[ { Title:'ID', dataIndex:'id' }, { Title:'NAME', dataIndex:'name' }, { Title:'AGE', dataIndex:'age' } ]; return ( <div> <UserModal record={ {} } ok={ createUser }> <Button type="primary">NEW</Button> </UserModal> <Table columns={ columns } dataSource={ list } rowKey={ t=>t.id } pagination={ false }> {/* users datatable */} </Table> </div> ); }; export default connect(({ user }) => { console.log(user); return { list: user.list }; })(UserTable);複製代碼
create.js
import React,{ Component } from 'react'; import { Modal,Form,Input } from 'antd'; class UserModal extends Component{ constructor(props){ super(props); this.state={ visible:false }; } render(){ const { children,form:{ getFieldDecorator },record,ok }=this.props; const showModal=()=>{ this.setState({ visible:true }); }; const hideModal=()=>{ this.setState({ visible:false }); }; const save=()=>{ this.props.form.validateFields((err,val)=>{ //val ==> record // console.log(val); ok(val); hideModal(); }); }; return ( <div> <span onClick={ showModal }> { children } </span> <Modal title="Create User" visible={ this.state.visible } onCancel={ hideModal } onOk={ save }> <Form> <Form.Item label="Name"> { getFieldDecorator('name', { initialValue: record.name })(<Input />) } </Form.Item> <Form.Item> { getFieldDecorator('age',{ initialValue:record.age })(<Input />) } </Form.Item> </Form> </Modal> </div> ); }; } export default Form.create()(UserModal);複製代碼
usersPage.js
import { connect } from 'dva'; import Main from '../components/layout/main'; import UserTable from '../components/user/user'; const UserPage=()=>{ return ( <Main> <h1>UserPage</h1> <UserTable /> </Main> ); }; export default connect()(UserPage);複製代碼
或者 https://pan.baidu.com/s/1bo1R7o7