redux VS mobx (装饰器配合使用)
生活随笔
收集整理的這篇文章主要介紹了
redux VS mobx (装饰器配合使用)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前言:redux和mobx都是狀態(tài)管理器,避免父級(jí)到子級(jí)再到子子級(jí)嵌套單向數(shù)據(jù)流,可以邏輯清晰的管理更新共享數(shù)據(jù)。(刷新頁(yè)面redux儲(chǔ)蓄數(shù)據(jù)即消失) 配置使用裝飾器(使用高階函數(shù)包裝你的組件):
npm install babel-plugin-transform-decorators-legacy --save-dev
@observable number1 = 1
@observable number2 = 2
@computed getTotal(){
return this.number1 + this.number2 // 每當(dāng)監(jiān)視數(shù)據(jù)發(fā)生變化就會(huì)執(zhí)行@computed
} @action.bound getData= async() => { // bound是為了綁定this上下文(箭頭函數(shù)可不需要)let res = await get('接口地址')if (res.success) {runInAction(() => { // runInAction函數(shù)可異步修改@observable數(shù)據(jù)this.userInfo = res.data})}} } export default rootStore = new RootStore()
userInfo: store.userInfo,
total: store.getTotal
})) @observer class EmpRec extends Component {constructor(props) {super(props)}render() {return(<div>this.props.userInfo</div>
<div>this.props.total</div> // 3
)
}
}
npm install babel-plugin-transform-decorators-legacy --save-dev
.babelrc配置:
{"presets": ["react-app"],"plugins": [["import",{"libraryName": "antd","style": true}],"transform-decorators-legacy"] }當(dāng)使用react native的時(shí)候,下面這個(gè)預(yù)設(shè)可以代替 transform-decorators-legacy
"babel": {"presets": ["react-app","react-native-stage-0/decorator-support"]}, 一.redux redux.js文件: // 定義變量 const CODE_CHANGE = 'CODE_CHANGE' const NUMBER_LIST = 'NUMBER_LIST' const ERROR_MSG = 'ERROR_MSG'// 初始化數(shù)據(jù) const initState = {industryNumber: storage.get('industryNumber'),numberList: [],msg: '' }// reducer export function isNumber(state = initState, action) {switch (action.type) {case CODE_CHANGE:return { ...state, industryNumber: action.industryNumber }case NUMBER_LIST:return { ...state, numberList: action.numberList }case ERROR_MSG:return { ...state, msg: action.msg }default:return state} }reducer.js文件:
import { combineReducers } from 'redux' import { isNumber } from '/redux'export default combineReducers({ isNumber }) // 合并所有的reducer,并且返回index.js入口文件:
import React from 'react' import ReactDOM from 'react-dom' import MainRouter from './Router'// 引入redux import { createStore, applyMiddleware, compose } from 'redux' importthunk from 'redux-thunk' // 中間插件,增強(qiáng)dispatch功能,可異步加載action可接受函數(shù)參數(shù) import { Provider } from 'react-redux' //redux組件,全部子級(jí)可以直接更新redux的state import reducers from './reducer' // 這里判斷瀏覽器環(huán)境是否開(kāi)啟Redux DevTools的插件(chrome瀏覽器擴(kuò)展插件應(yīng)用商店下載) const reduxDevtools = window.devToolsExtension ? window.devToolsExtension() : h => h //沒(méi)有插件則返回空函數(shù) const store = createStore(reducers, compose( applyMiddleware(thunk), reduxDevtools )) // 創(chuàng)建store ReactDOM.render( <Provider store={store}> <MainRouter/> //路由 </Provider>, document.getElementById('root') )某子組件:
import { connect } from 'react-redux' // 裝飾器 const fetchNumberList = () => { return dispatch => { // 異步請(qǐng)求需要 dispatch => {}包裹fetch('異步請(qǐng)求').then(res => {if (res.code === 0) {dispatch({ type: 'NUMBER_LIST', numberList: res.data })} })} }@connect(state => state.isNumber, // 如果有多個(gè)reducer: state => ({ ..state.isNumber, ...state.someName }){ fetchNumberList } // 一些之前寫(xiě)好的action方法 ) class IndustryManagement extends Component {constructor(props) {super(props)this.state= {industryNumber: this.props.industryNumber && this.props.industryNumber[0], // 直接props引用redux的state }}btnChange() {this.props.fetchNumberList() //經(jīng)過(guò)裝飾器的函數(shù)都可用props引用 }render() {return (<button onClick={ this.btnChange.bind(this) }>)} }?二.?mobx
這里推薦使用mobx-state-tree的寫(xiě)法,有興趣的可去github上看用法,以下是傳統(tǒng)寫(xiě)法:
store.js文件: import { observable, action, runInAction } from 'mobx' // runInAction接受異步action class RootStore { @observable userInfo = null //注冊(cè)變量并監(jiān)視變化(可以是引用類型值或者普通值)@observable number1 = 1
@observable number2 = 2
@computed getTotal(){
return this.number1 + this.number2 // 每當(dāng)監(jiān)視數(shù)據(jù)發(fā)生變化就會(huì)執(zhí)行@computed
} @action.bound getData= async() => { // bound是為了綁定this上下文(箭頭函數(shù)可不需要)let res = await get('接口地址')if (res.success) {runInAction(() => { // runInAction函數(shù)可異步修改@observable數(shù)據(jù)this.userInfo = res.data})}} } export default rootStore = new RootStore()
index.js入口文件:
import { Provider } from 'mobx-react' // 與上文的redux的Provider相似 import rootStore from './store' ReactDOM.render(<Provider rootStore={rootStore}> <MainRouter /> </Provider>,document.getElementById('root'))某子組件:
import { observer, inject } from 'mobx-react' @inject(({store, otherStore}) => ({ // 選擇注入store(如果有多個(gè)store),如果不用inject函數(shù)可直接import store from '../store',組件中直接store.userInfo使用userInfo: store.userInfo,
total: store.getTotal
})) @observer class EmpRec extends Component {constructor(props) {super(props)}render() {return(<div>this.props.userInfo</div>
<div>this.props.total</div> // 3
)
}
}
?對(duì)比下來(lái)感覺(jué)mobx比redux好用(逃~)
轉(zhuǎn)載于:https://www.cnblogs.com/xiaoxiao666/p/8873552.html
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的redux VS mobx (装饰器配合使用)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: OSI协议和TCP/IP协议笔记
- 下一篇: 力神电池股票代码