react-dva 的使用 简单的用法

首先看 他的核心模块 也是经常用到的模块 

1 module 模块  

/**
 * Created by guangqiang on 2017/12/17.
 */
import queryString from 'query-string';
import * as todoService from '../services/todo'

export default {
  namespace: 'todo', //model的命名空间,只能是命名空间。 也是全局state上的属性  
   state: {  //状态的初始值
     list: [],
     message:"ffff"
   },

  //类似于redux的 reducer 是一个纯函数用来处理同步函数。 是唯一一个可以修改 state的地方,由action触发
  //它有action和state两个参数 
  reducers: {   
    save(state, { payload: { list } }) {
      return { ...state, list }
    },

    saveq(state, { payload: { message } }) {     
      return { ...state, message }
    },
  },
//用于处理异步操作,不能直接修改state 由action触发 也可触发action  只能是generator 函数
//有两个参数 action ,effects 两个参数。第二个参数effect包括三个参数 (call,put,select)
//put 用于触发action ,call用于调用异步处理逻辑,select用于从state获取数据

  effects: {
    *addTodo({ payload: value }, { call, put, select }) {
      // 模拟网络请求
      const data = yield call(todoService.query, value)
      console.log(data)
      let tempList = yield select(state => state.todo.list)
      let list = []
      list = list.concat(tempList)
      const tempObj = {}
      tempObj.title = value
      tempObj.id = list.length
      tempObj.finished = false
      list.push(tempObj)
      yield put({ type: 'save', payload: { list }}) //put 用于触发action ,
    },
    *toggle({ payload: index }, { call, put, select }) {
      // 模拟网络请求
      const data = yield call(todoService.query, index)
      let tempList = yield select(state => state.todo.list)
      let list = []
      list = list.concat(tempList)
      let obj = list[index]
      obj.finished = !obj.finished
      yield put({ type: 'save', payload: { list } })
    },
    *delete({ payload: index }, { call, put, select }) {
      const data = yield call(todoService.query, index)
      let tempList = yield select(state => state.todo.list)
      let list = []
      list = list.concat(tempList)
      list.splice(index, 1)
      yield put({ type: 'save', payload: { list } })//put 用于触发action ,
    },

    *modify({ payload: { value, index } }, { call, put, select }) {
      const data = yield call(todoService.query, value)
      let tempList = yield select(state => state.todo.list)
      let list = []
      list = list.concat(tempList)
      let obj = list[index]
      obj.title = value
      yield put({ type: 'save', payload: { list } })
    },


    *test({ payload: message }, { call, put, select }) {
      console.log(message);
      yield put({ type: 'saveq', payload: { message } })//put 用于触发action ,
    }
  },

  //用于订阅某些数据 并根据情况dsipatch某些action 格式为 ({ dispatch, history }, done) => unlistenFunction。
  //监听路由的变化,当路径为todolist时就调用 action
  subscriptions: {
    setup({ dispatch, history }) {
      // 监听路由的变化,请求页面数据
      return history.listen(({ pathname, search }) => {
        const query = queryString.parse(search)
        console.log(query);
        let list = []
        if (pathname === 'todoList') {
          dispatch({ type: 'save', payload: {list} }) //
        }
      })
    }
  }
    //  注意,在 model 中触发这个 model 中的 action 时不需要写命名空间,比如在 fetch 中触发 save 时是 { type: 'save' }。而在组件中触发 action 时就需要带上命名空间了,比如在某个组件中触发 fetch 时,应该是 { type: 'user/fetch' }。
    //例如 
    //  this.props.dispatch({
    //   type: 'todo/delete', 加上命名空间
    //   payload: index
    // })

}

如何调用 module里面的方法呢 看代码 

 

/**
 * Created by guangqiang on 2017/12/17.
 */
import React, {Component} from 'react'
import styles from './TodoList.css'
import {connect} from 'dva'

class TodoList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      value: ''
    }
  }

  componentDidMount() {
  }

  removeItem(index) {
    this.props.dispatch({
      type: 'todo/delete',
      payload: index
    })
  }

  toggleItem(index) {
    this.props.dispatch({
      type: 'todo/toggle',
      payload: index
    })
  }

  modify(value, index) {
    this.props.dispatch({
      type: 'todo/modify',
      payload: {value, index}
    })
  }

  addTodo(value) {
    this.props.dispatch({
      type: 'todo/addTodo',
      payload: value
    })
    this.setState({value: ''})
  }

  test(value){
    console.log(value);
     this.props.dispatch({
       type:"todo/test",
       payload:value
     })
  }

  Tex(value){  
    this.props.dispatch({
      type:"example/fetch",
      payload:value
    })
  }

  render() {
    const { list, message} = this.props
    let count = 0
    list.map(item => count = !item.finished ? count + 1 : count)
    return (
      <div className={styles.container}>
        <span>
          <h1 onClick={()=>this.Tex('fff')}>我的测试</h1>
          <h1>我的待办清单</h1>
          <h1 onClick={() => this.test("fffkkkk")}>点击事件{message}</h1>
          <h3>你有{count}项待办事项未处理</h3>
        </span>
        <input
          style={{borderWidth: 1, borderColor: 'red'}}
          placeholder="请输入代办事项"
          value={this.state.value}
          onChange={(e) => this.setState({value: e.target.value})}
          onKeyDown={(e) => {
            if (e.keyCode === 13){
              let title = e.target.value
              title.length > 0 ? this.addTodo(title) : null
            }
          }}
        />
        <span>
          <ul>
            {
              list.map((item, index) => {
                return (
                  <li
                    key={index}
                  >
                    <input
                      type="checkbox"
                      checked={item.finished}
                      onChange={() => this.toggleItem(index)}
                    />
                    <input
                      style={{width: 200,height: 20}}
                      defaultValue={item.title}
                      autoFocus={false}
                      onKeyDown={(e) => {
                        if (e.keyCode === 13){
                          let title = e.target.value
                          this.modify(title, index)
                        }
                      }}
                    />
                    <button onClick={() => this.removeItem(index)}>删除</button>
                  </li>
                )
              })
            }
          </ul>
        </span>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    list: state.todo.list,
    message:state.todo.message

  }
}

const _todoList = connect(mapStateToProps)(TodoList)

export default _todoList

这个dispatch 的方法就是用来调用 

这个module 里面的方法的 

 

这段代码就是把  module 里面的 state 与react 组件里面的state 关联起来。这个时候就可以用dva 里面的state了 。

module 里面的state 与 react 里面的state 本身是没有关联的 。

  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值