加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

详解在React里使用"Vuex"

发布时间:2020-12-17 02:28:38 所属栏目:百科 来源:网络整理
导读:一直是Redux的死忠党,但使用过Vuex后,感叹于Vuex上手之快,于是萌生了写一个能在React里使用的类Vuex库,暂时取名 。 如何使用 一:创建Store实例: 与vuex一样,使用单一状态树(一个对象)包含全部的应用层级状态(store)。 store可配置state,mutations,acti

一直是Redux的死忠党,但使用过Vuex后,感叹于Vuex上手之快,于是萌生了写一个能在React里使用的类Vuex库,暂时取名 。

如何使用

一:创建Store实例:

与vuex一样,使用单一状态树(一个对象)包含全部的应用层级状态(store)。

store可配置state,mutations,actions和modules属性:

  1. state :存放数据
  2. mutations :更改state的唯一方法是提交 mutation
  3. actions :Action 提交的是 mutation,而不是直接变更状态。Action 可以包含任意异步操作,触发mutation,触发其他actions。

支持中间件:中间件会在每次mutation触发前后执行。

store.js:

{ commit('add',payload) },1000) },addPromise({state,payload){ return fetch('https://api.github.com/search/users?q=haha').then(res=>res.json()) .then(res=>{ commit('add',1) dispatch('addAsync',1) }) },doubleAsync({state,payload){ setTimeout(()=>{ commit('double',2) },doublePromise({state,payload){ return fetch('https://api.github.com/search/users?q=haha').then(res=>res.json()) .then(res=>{ commit('double',2) dispatch('doubleAsync',2) }) },} // middleware const logger = (store) => (next) => (mutation,payload) =>{ console.group('before emit mutation ',store.getState()) let result = next(mutation,payload) console.log('after emit mutation',store.getState()) console.groupEnd() } // create store instance const store = createStore({ state,actions,},[logger]) export default store

将Store实例绑定到组件上

ruex提供Provider方便store实例注册到全局context上。类似react-redux的方式。

App.js:

) } }

使用或修改store上数据

store绑定完成后,在组件中就可以使用state上的数据,并且可以通过触发mutation或action修改state。具体的方式参考react-redux的绑定方式:使用connect高阶组件。

Child1.js:

render() {
const {
total_num,} = this.props
return (


) } }

const mapStateToProps = (state) => ({
total_num:state.total_num,})
const mapMutationsToProps = ['add','double']
const mapActionsToProps = ['addAsync','addPromise','doubleAsync','doublePromise']

export default connect(
mapStateToProps,mapMutationsToProps,mapActionsToProps,)(Chlid1)

API:

  1. mapStateToProps :将state上的数据绑定到当前组件的props上。
  2. mapMutationsToProps : 将mutation绑定到props上。例如:调用时通过this.props.add(data)的方式即可触发mutation,data参数会被mutaion的payload参数接收。
  3. mapActionsToProps : 将action绑定到props上。

内部实现

ruex内部使用immer维护store状态更新,因此在mutation中,可以通过直接修改对象的属性更改状态,而不需要返回一个新的对象。例如:

支持modules(暂不支持namespace)

支持中间件。注:actions已实现类似redux-thunk的功能

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读