第一步
安装DVA
$ npm install -g dva-cli
创建一个项目
$ dva new myapp --demo
$ cd myapp
$ npm run start
创建Component
$ dva g component count
基础代码如下:
import React from 'react'; import styles from './Count.css'; function Count() { return ( <div className={styles.normal}> Component: Count </div> ); } export default Count;
经修改,相关代码如下:
import React from 'react'; import styles from './Count.css'; function Count(count,dispatch) { return ( <div className={styles.normal}> <div className={styles.record}>Highest Record: {count.record}</div> <div className={styles.current}>{count.current}</div> <div className={styles.button}> <button onClick={() => { dispatch({type: 'count/add'}); }}>+</button> </div> </div> ); } export default Count;
创建 Model
Model
可以理解为 Action的集合,里面有Reducer,Effect、Subsctiption
$ dva g model count基础代码如下:
export default { namespace: 'count',state: {},reducers: {},effects: {},subscriptions: {},};
经修改 初始化,加入Action 即 相关方法,完整代码如下:
export default { namespace: 'count',state: { record: 0,current: 0,},reducers: { add(state) { const newCurrent = state.current + 1; return { ...state,record: newCurrent > state.record ? newCurrent : state.record,current: newCurrent,}; },minus(state) { return { ...state,current: state.current - 1}; },};
import dva,{ connect } from 'dva'; import { Router,Route } from 'dva/router'; import fetch from 'dva/fetch'; import React from 'react'; import './index.html'; import Count from './components/Count'; // 1. Initialize const app = dva(); // 2. Model // Remove the comment and define your model. //app.model({}); // 3. Router const HomePage = () => <div>Hello Dva.</div>; app.model(require("./models/count")); app.router(({ history }) => <Router history={history}> <Route path="/" component={Count} /> </Router> ); // 4. Start app.start('#root');
$ npm run start
可以显示 我们组件的内容了 ,这说明我们已成功了 第一步
第二步
把Component 与Model 关联,使得 初始化有值,点击 事件生效
import React from 'react'; import styles from './Count.css'; import {connect} from 'dva' function Count({count,dispatch}) { return ( <div className={styles.normal}> <div className={styles.record}>Highest Record: {count.record}</div> <div className={styles.current}>{count.current}</div> <div className={styles.button}> <button onClick={() => { dispatch({type: 'count/add'}); }}>+</button> </div> </div> ); } function mapStateToProps(state) { return state; } export default connect(mapStateToProps)(Count);
核心代码说明 ,主要是 通过 connect 把 model 与Component关联起来
export default connect(mapStateToProps)(Count);
传入参数 ,用{} 包起来。
Count({count,dispatch})
mapStateToProps
如果以上已完成,恭喜你,完成了 简单的 Demo
原文链接:https://www.f2er.com/react/302913.html