Dva: effect执行问题

Created on 6 Sep 2017  ·  1Comment  ·  Source: dvajs/dva

根据https://github.com/dvajs/dva/blob/master/docs/GettingStarted.md,写了几乎一模一样的代码:

import dva, { connect } from 'dva';
import { Router, Route } from 'dva/router';
import React from 'react';
import styles from './index.less';

const app = dva();

app.model({
  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: {
    *add(action, { call, put }) {
      yield call(delay, 1000);
      yield put({ type: 'minus' });
    },
  },
});

const CountApp = ({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 { count: state.count };
}
const HomePage = connect(mapStateToProps)(CountApp);

app.router(({history}) =>
  <Router history={history}>
    <Route path="/" component={HomePage} />
  </Router>
);

app.start('#root');


// ---------
// Helpers

function delay(timeout){
  return new Promise(resolve => {
    setTimeout(resolve, timeout);
  });
}

但是点击按钮之后数值没有增加,只会过一秒之后减少,所以出现了负数
image

如果去掉effect部分,功能正常。这个怎么破?

>All comments

那个例子有问题,dva@2 之后不允许 reducers 和 effects 同名,你换个名字就好了。参考这个例子:https://stackblitz.com/edit/dva-example-count-2?file=index.js

Was this page helpful?
0 / 5 - 0 ratings