当前位置: 首页 > 编程笔记 >

详解在React里使用"Vuex"

聂风史
2023-03-14
本文向大家介绍详解在React里使用"Vuex",包括了详解在React里使用"Vuex"的使用技巧和注意事项,需要的朋友参考一下

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

如何使用

一:创建Store实例:

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

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

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

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

store.js:

import {createStore} from 'ruex'
const state = {
 total_num:1111,
}
const mutations = {
 add(state,payload){
 state.total_num += payload
 },
 double(state,payload){
 state.total_num = state.total_num*payload
 },
}
const actions = {
 addAsync({state,commit,rootState,dispatch},payload){
 setTimeout(()=>{
 commit('add',payload)
 },1000)
 },
 addPromise({state,commit,rootState,dispatch},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,commit,rootState,dispatch},payload){
 setTimeout(()=>{
 commit('double',2)
 },1000)
 },
 doublePromise({state,commit,rootState,dispatch},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,
 mutations,
 actions,
},[logger])
export default store

将Store实例绑定到组件上

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

App.js:

import React from 'react'
import {Provider} from 'ruex'
import store from './store.js'
class App extends React.Component{
 render(){
 return (
  <Provider store={store} >
  <Child1/>
  </Provider>
 )
 }
}

使用或修改store上数据

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

Child1.js:

import React, {PureComponent} from 'react'
import {connect} from 'ruex'
class Chlid1 extends PureComponent {
 state = {}
 constructor(props) {
 super(props);
 }

 render() {
 const {
 total_num,
 } = this.props
 return (
 <div className=''>
 <div className="">
 total_num: {total_num}
 </div>

 <button onClick={this.props.add.bind(this,1)}>mutation:add</button>
 <button onClick={this.props.addAsync.bind(this,1)}>action:addAsync</button>
 <button onClick={this.props.addPromise.bind(this,1)}>action:addPromise</button>
 <br />
 <button onClick={this.props.double.bind(this,2)}>mutation:double</button>
 <button onClick={this.props.doubleAsync.bind(this,2)}>action:doubleAsync</button>
 <button onClick={this.props.doublePromise.bind(this,2)}>action:doublePromise</button>
 </div>)
 }
}


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中,可以通过直接修改对象的属性更改状态,而不需要返回一个新的对象。例如:

const state = {
 obj:{
 name:'aaaa'
 }
}
const mutations = {
 changeName(state,payload){
 state.obj.name = 'bbbb'
 // instead of 
 // state.obj = {name:'bbbb'}
 },
}

支持modules(暂不支持namespace)

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持小牛知识库。

 类似资料:
  • 本文向大家介绍React Native react-navigation 导航使用详解,包括了React Native react-navigation 导航使用详解的使用技巧和注意事项,需要的朋友参考一下 一、开源库介绍 今年1月份,新开源的react-natvigation库备受瞩目。在短短不到3个月的时间,github上星数已达4000+。Fb推荐使用库,并且在React Native当前最

  • 本文向大家介绍Docker 7 docker在阿里云的使用详解,包括了Docker 7 docker在阿里云的使用详解的使用技巧和注意事项,需要的朋友参考一下 在传统模式中,开发团队在开发环境中完成软件开发,自己做了一遍单元测试, 测试通过,ᨀ交到代码版本管理库。运维把应用部署到测 试环境, QA 进行测试,没问题后通知部署人员发布到生产环境。 在上述过程中涉及到至少三个环境:开发、测试和生产。现

  • 本文向大家介绍详解react使用react-bootstrap当轮子造车,包括了详解react使用react-bootstrap当轮子造车的使用技巧和注意事项,需要的朋友参考一下 上一篇我们谈了谈如何配置react的webpack环境 react入门之搭配环境(一) 可能很多人已经打开过官方文档学习了react的基础知识 不管有没有,在介绍react之前,我想先介绍一下react-bootstra

  • 本文向大家介绍详解React之key的使用和实践,包括了详解React之key的使用和实践的使用技巧和注意事项,需要的朋友参考一下 在渲染列表时,React的差异比较算法需要一个在列表范围内的唯一key来提高性能(通常用于获知哪个列表项改变了)。这个唯一的key需要我们手动提供。React官方建议使用列表数据中可用于唯一性标识的字段来作为列表项渲染时的key。如果实在没有,则可使用数组的index

  • 主要内容:一、SPI是什么?,Services里的SPI,Dubbo.internal里的SPI一、SPI是什么?         SPI是中间件设计不可缺少的一项,SPI能提高应用的可插拔性,SPI的英文全称: Service Provider Implementation, 我们可以在META-INF目录里配置SPI, ServiceLoader会根据配置来找到接口的实现,那Dubbo里的@SPI又是什么呢?         Dubbo的Common模块里,定义了一个@SPI注解,该注解

  • 本文向大家介绍详解使用React进行组件库开发,包括了详解使用React进行组件库开发的使用技巧和注意事项,需要的朋友参考一下 最近针对日常业务需求使用react封装了一套[组件库], 大概记录下整个开发过程中的心得。由于篇幅原因,在这里只对开发过程中比较纠结的选型和打包等进行讨论,后续再对具体组件的封装进行讨论。 概述 我们都知道,组件化的开发模式对于我们的开发效率有着极大的提升,针对我们日常使