import dva from 'dva';
import { Router, Route, Switch } from 'dva/router';
import styles from './index.less';
import Content from './Conten';
import {connect} from 'dva';
// 在定义了 Model 和 Component 之后,我们需要把它们连接起来。这样 Component 里就能使用 Model 里定义的数据,而 Model 中也能接收到 Component里 dispatch 的 action
const CountApp = ({count, dispatch}) => {
return (
<div className={styles.normal}>
<Content/>
<div className={styles.record}>Highest Record: {count.record}</div>
<div className={styles.current}>{count.current}</div>
<div className={styles.button}>
{/*dispatch 是一个函数方法,用来将 Action 发送给 Model 中的State。
dispatch方法从哪里来?被 connect 的 Component 会自动在 Props 中拥有 dispatch 方法。
*/}
<button onClick={() => { dispatch({type: 'count/add'}); }}>+</button>
<button onClick={() => {dispatch({type:'count/minus'}); }}>-</button>
<button onClick={() => {dispatch({type:'count/showPic'});}}>show</button>
</div>
{count.show?<img src="1.jpeg" alt="新垣结衣"/>:null}
</div>
);
};
function mapStateToProps (state) {
return {
count:state.count
};
}
//connect 方法返回的也是一个 React 组件,通常称为容器组件。因为它是原始 UI 组件的容器,即在外面包了一层 State
//connect 方法传入的第一个参数是 mapStateTOProps 函数,这个函数返回一个对象,用于建立 State 到 Props 的映射关系。
const HomePage = connect(mapStateToProps)(CountApp);
// 1. Initialize
const app = dva();
// 2. Model
// model 对象的属性
// namespace : 当前 Model 的名称。整个应用的 State,由多个小的 Model 的 State 以 namespace 为 key 合成。
//state:该 MOdel 当前的状态。数据保存在这里,直接决定了视图层的输出。
//reducers:Action 处理器。处理同步动作,算出最新的 State 。
//effects:Action 处理器。处理异步动作 。
app.model({
namespace: 'count',
state: {
record: 0,
current: 0,
show: 0,
},
reducers: {
// add(){} 等同于 add:fucntion(){}
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
};
},
showPic(state) {
return {
...state,
show: !state.show
}
}
},
})
// Effect 指的是副作用。根据函数式编程,计算以外的操作都属于 Effect,典型的就是 I/O操作、数据库读写。
// Effect 是一个 Generator函数,内部使用 yield 关键字,标识每一步的操作(不管是同步还是异步)。
// dva 提供多个 effect 函数内部的处理函数,比较常用的是 call 和 put。
// call 函数:执行异步操作
// put 函数:发出一个Action,类似于 dispatch
// 3. Router
// 接收到 url 之后决定渲染哪些 Component,这是由路由决定
// const HomePage = () => <div>Hello Dva.</div>;
app.router(({ history }) =>
<Router history={history}>
<Switch>
<Route path="/" exact component={HomePage} />
</Switch>
</Router>
);
// 4. Start
app.start('#root');