一直是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的功能

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

点赞(119)

评论列表共有 0 条评论

立即
投稿
返回
顶部