其他分享
首页 > 其他分享> > dva、immer使用

dva、immer使用

作者:互联网

dva文档

immer 使用文档

### immer 作用

###### immer 使用

 this.setState((prevState) => {
      return produce(prevState, draftState =>{
        draftState.address.city.area = 'JingAn';
        draftState.address.city.postcode = draftState.address.city.postcode + 10;
      });
  });

dva 注册

import dva from 'dva';
import './index.css';

// 1. Initialize
const app = dva();

// 2. Plugins
// app.use({});

// 3. Model
app.model(require('./models/network').default);

// 4. Router
app.router(require('./router').default);

// 5. Start
app.start('#root');

dva models

./models/network 文件
import request from '../utils/request';
import { produce } from 'immer';

export default {
  namespace: 'network',
  state: {
    info: {
      relationship: '同学',
    },
    list: [
      { name: '源', age: 26, city: '北京' },
    ],
    articles: [],
  },

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line
    },
  },

  effects: {
    *getList({ value }, { call, put }) {  // eslint-disable-line
      const res = yield call(request, value.url)
      console.log(res.data.data.articles, 'km')
      yield put({ type: 'save', value: res?.data?.data?.articles || [] });
    },
  },

  reducers: {
    save(state, action) {
      return produce(state, draftState => {
        draftState.articles = action.value;
      })
    },
    add(state, action) {
      return produce(state, draftState => {
        draftState.list = [...draftState.list, action.value]
      })
    }
  },

};

页面使用

import React, { useEffect } from 'react';
import { connect } from 'dva';

function IndexPage({ dispatch, network }) {

  const addNeteork = () => {
    dispatch({ type: 'network/add', value: { name: '婷', age: 24, city: '北京' } })
    console.log(network, 'network')
  }

  useEffect(() => {
    dispatch({ type: 'network/getList', value: { url: '' } }) // url 接口地址
  }, [])

  return (
    <div>
      <button onClick={addNeteork}>添加关系</button>
    </div>
  );
}

IndexPage.propTypes = {
};

export default connect(({ network }) => ({ network }))(IndexPage);

标签:network,draftState,dva,value,immer,state,使用
来源: https://www.cnblogs.com/yuan-190214/p/15956146.html