Dva React 入门 Demo 篇章 2
发布时间:2020-12-15 06:50:08 所属栏目:百科 来源:网络整理
导读:本文章是基于上一篇文章来解说的,很多代码一样,只要稍微修改即可。 从dva框架,我们可以看得出 ,分如下 四部分 component 业务组件 model 可以理解为 function集合, service 调用服务端 相关接口,model 会调用service route 会调用相关的 component 拼成
本文章是基于上一篇文章来解说的,很多代码一样,只要稍微修改即可。
从dva框架,我们可以看得出 ,分如下 四部分
component 业务组件 model 可以理解为 function集合, service 调用服务端 相关接口,model 会调用service route 会调用相关的 component 拼成 一个完整,可显示的组件。
第一步 创建一个新的项目$ dva new myapp 注意 要去掉 --demo
第二步 创建 component$ dva g component count Components/Count.js 相关代码如下: import React from 'react'; import styles from './Count.css'; function Count({count,clickHandle}) { 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={ clickHandle }>+</button> </div> </div> ); } export default Count 第三步 创建 Model$ dva g model count models/Count.js 相关代码如下: 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}; },effects: {},subscriptions: {},}; 第四步 创建 Route$ dva g route count Routes/Count.js 相关代码如下: import React from 'react'; import { connect } from 'dva'; import styles from './Count.css'; import CP from '../components/Count'; function Count({count,dispatch}) { function myClick() { dispatch({type: 'count/add'}); } return ( <CP clickHandle={myClick} count={count} /> ); } export default connect(({ count }) => ({count}))(Count); $ npm run start 浏览器 输入http://localhost:8000/#/count 可看到运行效果。
关键代码解说1. 我们把 connect 放到了 routes ,通过 把 function 和相关的参数 传入Component,这样实现了解耦, 传参如下: <CP clickHandle={myClick} count={count} /> 把model里面的数据绑定到 route里面,关键代码如下: export default connect(({ count }) => ({count}))(Count);注意 :count值要与 model里面的 namespace对应,我们只把对应的 state传入 组件 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |