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

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

时间:2023-03-31 21:40:05 vue.js

这是关于React和Vue语法比较的第三篇文章。在本文中,将比较两个生态系统中最著名的状态管理库(Redux和Vuex)的语法。另外两篇文章:React.js和Vue.js的语法比较Next.js和Nuxt.js的语法比较Agenda创建StoreAction异步ActionReducer|MutationCombine-Reducers|ModulesConnect-with-Component中间件|插件选择器|GetterDevTools创建StoreRedux:https://redux.js.org/basics/s...importReactfrom'react'import{render}from'react-dom'import{Provider}from'react-redux'import{createStore}from'redux'importtodoAppfrom'./reducers'importAppfrom'./components/App'conststore=createStore(todoApp)render(,文档。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,文本,}}Vuex:https://vuex.vuejs.org/guide/...conststore=newVuex.Store({actions:{increment(context){context.commit('increment')//提交突变以触发状态更新}}})异步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,{文本: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'../components/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'exportdefault{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('dispatching',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]:[],})选择器|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=>{返回{做neTodos:getDoneTodos(state)}}constDoneTodoList=connect(mapStateToProps)(TodoList)导出默认DoneTodoListVuex:https://vuex.vuejs.org/guide/...conststore=newVuex.Store({state:{.。.mapGetters(['doneTodos'])}}DevToolsReduxhttps://chrome.google.com/web...Vuexhttps://chrome.google.com/web...来源:https://medium.com/js-dojo,作者:Oahehc(Andrew),翻译:公众号《前端全栈开发者》