当前位置: 首页 > Web前端 > vue.js

React和Vue语法并排:状态管理

时间:2023-03-31 19:41:52 vue.js

这是React和Vue语法比较的第二篇文章。在本文中,将比较两个生态系统中最著名的状态管理库(Redux和Vuex)的语法。上一篇:React.js和Vue.js的语法并排比较AgendaCreateStoreActionAsynchronousActionReducer|MutationCombine-Reducers|模块连接组件中间件|插件选择器|GetterDevTools创建StoreRedux:https://redux.js.org/basics/s...importReactfrom'react'import{render}from'react-dom'import{Provider}from'react-redux'import{createStore}从'redux'从'./reducers'导入todoApp从'./components/App'conststore=createStore(todoApp)render(,document.getElementById('root'))Vuex:https://vuex.vuejs.org/guide/conststore=newVuex.Store({state:{...},mutations:{...}})...newVue({el:'#app',store,});ActionRedux:https://redux.js.org/basics/a...constADD_TODO='ADD_TODO'functionaddTodo(text){返回{类型:ADD_TODO,text,}}Vuex:https://vuex.vuejs.org/guide/...conststore=newVuex.Store({actions:{increment(context){context.commit('increment')//comm它是触发状态更新的突变}}})异步ActionRedux(redux-thunk):https://redux.js.org/advanced...//applyredux-thunkimportthunkMiddlewarefrom'redux-thunk'conststore=createStore(rootReducer,applyMiddleware(thunkMiddleware))...exportfunctionfetchPosts(){returnfunction(dispatch){dispatch(requestPosts())returnfetch('xxx').then(response=>response.json()).then(json=>dispatch(receivePosts(json)))}}Vuex:https://vuex.vuejs.org/guide/...actions:{asyncfetchPosts({commit}){commit('requestPosts');constres=awaitfetch('xxx');commit('receivePosts',res);},}减速机|MutationRedux(reducer):https://redux.js.org/basics/r...constinitialState={todos:[],}functiontodoApp(state=initialState,action){switch(action.type){caseADD_TODO:return{...state,todos:[...state.todos,{text:action.text,completed:false,}],}default:returnstate}}Vuex(mutation):https://vuex.vuejs.org/guide/...conststore=newVuex.Store({mutations:{addTodo(状态,payload){state.todos=[...state.todos,{text:payload.text,completed:false}]}}})Combine-Reducers|复制代码ModulesRedux(combine-reducers):https://redux.js.org/api/comb...import{combineReducers}from'redux'constreducers=combineReducers({reducerA,reducerB,})exportdefaultreducersVuex(modules):https://vuex.vuejs.org/guide/...constmoduleA={state:{...},mutations:{...},actions:{...},getters:{...}}constmoduleB={state:{...},mutations:{...},actions:{...}}conststore=newVuex.Store({modules:{a:moduleA,b:moduleB}})Connect-with-ComponentRedux:https://redux.js.org/basics/u...import{connect}from'react-redux'import{addTodo}from'../actions'importTargetCompfrom'../补偿onents/TargetComp'//stateconstmapStateToProps=(state,ownProps)=>{return{todos:state.todos,}}//actionconstmapDispatchToProps=(dispatch,ownProps)=>{return{addTodo:(text)=>{}dispatch(addTodo(text))}}}constTargetContainer=connect(mapStateToProps,mapDispatchToProps)(TargetComp)导出默认TargetContainerVuexstate:https://vuex.vuejs.org/guide/...import{mapState}from'vuex'export默认{computed:{...mapState(['count']),}}action:https://vuex.vuejs.org/guide/...import{mapActions}from'vuex'exportdefault{methods:{...mapActions(['increment']),}}中间件|插件Redux(middleware):https://redux.js.org/advanced...import{createStore,combineReducers,applyMiddleware}from'redux'constlogger=store=>next=>action=>{console.log('调度',action)letresult=next(action)console.log('nextstate',store.getState())returnresult}consttodoApp=combineReducers(reducers)conststore=createStore(todoApp,applyMiddleware(logger))Vuex(plugin):https://vuex.vuejs.org/guide/...constmyPluginWithSnapshot=store=>{让prevState=_.cloneDeep(store.state)store.subscribe((mutation,state)=>{letnextState=_.cloneDeep(state)//比较`prevState`和`nextState`...//为下一个突变保存状态prevState=nextState})}conststore=newVuex.Store({...,plugins:process.env.NODE_ENV!=='production'?[myPluginWithSnapshot]:[],})Selector|GetterRedux(reselect):https://redux.js.org/recipes/...import{createSelector}from'reselect'constgetTodos=state=>state.todosexportconstgetDoneTodos=createSelector([getTodos],todos.filter(t=>t.completed),)...import{connect}from'react-redux'importTodoListfrom'../components/TodoList'import{getDoneTodos}from'../selectors'constmapStateToProps=state=>{返回{doneTodos:getDoneTodos(state)}}constDoneTodoList=connect(mapStateToProps)(TodoList)导出默认DoneTodoListVuex:https://vuex.vuejs.org/guide/...conststore=newVuex.Store({state:{...},getters:{doneTodos:state=>{returnstate.todos.filter(t=>t.completed)}}})...import{mapGetters}from'vuex'exportdefault{computed:{...mapGetters(['doneTodos'])}}DevToolsReduxhttps://chrome.google.com/web...Vuexhttps://chrome.google.com/web...来源:https://medium.com/js-dojo,作者:Oahehc(Andrew),翻译:公众号《前端全栈开发者》