详解在React里使用"Vuex"
一直是Redux的死忠党,但使用过Vuex后,感叹于Vuex上手之快,于是萌生了写一个能在React里使用的类Vuex库,暂时取名 。 如何使用一:创建Store实例:与vuex一样,使用单一状态树(一个对象)包含全部的应用层级状态(store)。 store可配置state,mutations,actions和modules属性:
支持中间件:中间件会在每次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) => ({ export default connect( API:
内部实现ruex内部使用immer维护store状态更新,因此在mutation中,可以通过直接修改对象的属性更改状态,而不需要返回一个新的对象。例如: 支持modules(暂不支持namespace) 支持中间件。注:actions已实现类似redux-thunk的功能 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |