React+Dva

Reducer

  reducer 是一个函数,接受 state 和 action,返回老的或新的 state 。即:(state, action) => state

Effect

app.model({
  namespace: 'todos',
  effects: {
    *addRemote({ payload: todo }, { put, call }) {
      yield call(addTodo, todo);
      yield put({ type: 'add', payload: todo });
    },
  },
});

 Effects

   put:用于触发 action 。          yield put({ type: 'todos/add', payload: 'Learn Dva' })

   call:用于调用异步逻辑,支持 promise 。           const result = yield call(fetch, '/todos');

      select:用于从 state 里获取数据。      const todos = yield select(state => state.todos);

错误处理

  全局错误处理

  dva 里,effects 和 subscriptions 的抛错全部会走 onError hook,所以可以在 onError 里统一处理错误。

  const app = dva({
    onError(e, dispatch) {
      console.log(e.message);
    },
  })
  本地错误处理

  如果需要对某些 effects 的错误进行特殊处理,需要在 effect 内部加 try catch

异步请求

  GET 和 POST
  import request from '../util/request';
  // GET   request('/api/todos');
  // POST   request('/api/todos', {   method: 'POST',   body: JSON.stringify({ a: 1 }),   });

Subscription

  subscriptions 是订阅,用于订阅一个数据源,然后根据需要 dispatch 相应的 action。

 subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/users') {
          dispatch({
            type: 'users/fetch',
          });
        }
      });
    },
  },

Router

<Route path="/" component={App}>
  <Route path="statements" component={Statements}/>
</Route>

基于 action 进行页面跳转

import { routerRedux } from 'dva/router';

// Inside Effects
yield put(routerRedux.push('/logout'));

// Outside Effects
dispatch(routerRedux.push('/logout'));

// With query
routerRedux.push({
  pathname: '/logout',
  query: {
    page: 2,
  },
});

 

转载于:https://www.cnblogs.com/JunneHu/p/7553124.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值