詳解在React里使用"Vuex"
一直是Redux的死忠黨,但使用過(guò)Vuex后,感嘆于Vuex上手之快,于是萌生了寫一個(gè)能在React里使用的類Vuex庫(kù),暫時(shí)取名 Ruex 。
如何使用
一:創(chuàng)建Store實(shí)例:
與vuex一樣,使用單一狀態(tài)樹(shù)(一個(gè)對(duì)象)包含全部的應(yīng)用層級(jí)狀態(tài)(store)。
store可配置state,mutations,actions和modules屬性:
- state :存放數(shù)據(jù)
- mutations :更改state的唯一方法是提交 mutation
- actions :Action 提交的是 mutation,而不是直接變更狀態(tài)。Action 可以包含任意異步操作,觸發(fā)mutation,觸發(fā)其他actions。
支持中間件:中間件會(huì)在每次mutation觸發(fā)前后執(zhí)行。
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實(shí)例綁定到組件上
ruex提供Provider方便store實(shí)例注冊(cè)到全局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上數(shù)據(jù)
store綁定完成后,在組件中就可以使用state上的數(shù)據(jù),并且可以通過(guò)觸發(fā)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:
- mapStateToProps :將state上的數(shù)據(jù)綁定到當(dāng)前組件的props上。
- mapMutationsToProps : 將mutation綁定到props上。例如:調(diào)用時(shí)通過(guò)this.props.add(data)的方式即可觸發(fā)mutation,data參數(shù)會(huì)被mutaion的payload參數(shù)接收。
- mapActionsToProps : 將action綁定到props上。
內(nèi)部實(shí)現(xiàn)
ruex內(nèi)部使用immer維護(hù)store狀態(tài)更新,因此在mutation中,可以通過(guò)直接修改對(duì)象的屬性更改狀態(tài),而不需要返回一個(gè)新的對(duì)象。例如:
const state = { obj:{ name:'aaaa' } } const mutations = { changeName(state,payload){ state.obj.name = 'bbbb' // instead of // state.obj = {name:'bbbb'} }, }
支持modules(暫不支持namespace)
支持中間件。注:actions已實(shí)現(xiàn)類似redux-thunk的功能
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
TypeScript在React項(xiàng)目中的使用實(shí)踐總結(jié)
這篇文章主要介紹了TypeScript在React項(xiàng)目中的使用總結(jié),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04React利用scheduler思想實(shí)現(xiàn)任務(wù)的打斷與恢復(fù)
這篇文章主要為大家詳細(xì)介紹了React如何利用scheduler思想實(shí)現(xiàn)任務(wù)的打斷與恢復(fù),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以參考一下2024-03-03React?hooks中useState踩坑之異步的問(wèn)題
這篇文章主要介紹了React?hooks中useState踩坑之異步的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03React Native自定義標(biāo)題欄組件的實(shí)現(xiàn)方法
今天講一下如何實(shí)現(xiàn)自定義標(biāo)題欄組件,我們都知道RN有一個(gè)優(yōu)點(diǎn)就是可以組件化,在需要使用該組件的地方直接引用并傳遞一些參數(shù)就可以了,這種方式確實(shí)提高了開(kāi)發(fā)效率。對(duì)React Native自定義標(biāo)題欄組件的實(shí)現(xiàn)方法感興趣的朋友參考下2017-01-01react中使用heatmap.js實(shí)現(xiàn)熱力圖的繪制
heatmap.js?是一個(gè)用于生成熱力圖的?JavaScript?庫(kù),React?是一個(gè)流行的?JavaScript?庫(kù),用于構(gòu)建用戶界面,本小編給大家介紹了在React?應(yīng)用程序中使用heatmap.js實(shí)現(xiàn)熱力圖的繪制的示例,文中通過(guò)代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12