欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

React和Vue中監(jiān)聽(tīng)變量變化的方法

 更新時(shí)間:2018年11月14日 08:44:49   作者:薄荷前端  
這篇文章主要介紹了React和Vue中監(jiān)聽(tīng)變量變化的方法,本文通過(guò)一個(gè)場(chǎng)景,父組件傳遞子組件一個(gè)A參數(shù),子組件需要監(jiān)聽(tīng)A參數(shù)的變化轉(zhuǎn)換為state,具體內(nèi)容詳情大家跟隨小編一起通過(guò)本文學(xué)習(xí)吧

React 中

本地調(diào)試React代碼的方法

yarn build

場(chǎng)景

假設(shè)有這樣一個(gè)場(chǎng)景,父組件傳遞子組件一個(gè)A參數(shù),子組件需要監(jiān)聽(tīng)A參數(shù)的變化轉(zhuǎn)換為state。

16之前

在React以前我們可以使用 componentWillReveiveProps 來(lái)監(jiān)聽(tīng) props 的變換

16之后

在最新版本的React中可以使用新出的 getDerivedStateFromProps 進(jìn)行props的監(jiān)聽(tīng), getDerivedStateFromProps 可以返回 null 或者一個(gè)對(duì)象,如果是對(duì)象,則會(huì)更新 state

getDerivedStateFromProps觸發(fā)條件

我們的目標(biāo)就是找到 getDerivedStateFromProps 的 觸發(fā)條件

我們知道,只要調(diào)用 setState 就會(huì)觸發(fā) getDerivedStateFromProps ,并且 props 的值相同,也會(huì)觸發(fā) getDerivedStateFromProps (16.3版本之后)

setState 在 react.development.js 當(dāng)中

Component.prototype.setState = function (partialState, callback) {
 !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : void 0;
 this.updater.enqueueSetState(this, partialState, callback, 'setState');
};
ReactNoopUpdateQueue {
 //...部分省略
 
 enqueueSetState: function (publicInstance, partialState, callback, callerName) {
 warnNoop(publicInstance, 'setState');
 }
}

執(zhí)行的是一個(gè)警告方法

function warnNoop(publicInstance, callerName) {
 {
 // 實(shí)例的構(gòu)造體
 var _constructor = publicInstance.constructor;
 var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
 // 組成一個(gè)key 組件名稱+方法名(列如setState)
 var warningKey = componentName + '.' + callerName;
 // 如果已經(jīng)輸出過(guò)警告了就不會(huì)再輸出
 if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
 return;
 }
 // 在開(kāi)發(fā)者工具的終端里輸出警告日志 不能直接使用 component.setState來(lái)調(diào)用 
 warningWithoutStack$1(false, "Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);
 didWarnStateUpdateForUnmountedComponent[warningKey] = true;
 }
}

看來(lái) ReactNoopUpdateQueue 是一個(gè)抽象類(lèi),實(shí)際的方法并不是在這里實(shí)現(xiàn)的,同時(shí)我們看下最初 updater 賦值的地方,初始化 Component 時(shí),會(huì)傳入實(shí)際的 updater

function Component(props, context, updater) {
 this.props = props;
 this.context = context;
 // If a component has string refs, we will assign a different object later.
 this.refs = emptyObject;
 // We initialize the default updater but the real one gets injected by the
 // renderer.
 this.updater = updater || ReactNoopUpdateQueue;
}

我們?cè)诮M件的構(gòu)造方法當(dāng)中將 this 進(jìn)行打印

class App extends Component {
 constructor(props) {
 super(props);
 //..省略

 console.log('constructor', this);
 }
} 

方法指向的是,在 react-dom.development.js classComponentUpdater

var classComponentUpdater = {
 // 是否渲染
 isMounted: isMounted,
 enqueueSetState: function(inst, payload, callback) {
 // inst 是fiber
 inst = inst._reactInternalFiber;
 // 獲取時(shí)間
 var currentTime = requestCurrentTime();
 currentTime = computeExpirationForFiber(currentTime, inst);
 // 根據(jù)更新時(shí)間初始化一個(gè)標(biāo)識(shí)對(duì)象
 var update = createUpdate(currentTime);
 update.payload = payload;
 void 0 !== callback && null !== callback && (update.callback = callback);
 // 排隊(duì)更新 將更新任務(wù)加入隊(duì)列當(dāng)中
 enqueueUpdate(inst, update);
 //
 scheduleWork(inst, currentTime);
 },
 // ..省略
}
enqueueUpdate

就是將更新任務(wù)加入隊(duì)列當(dāng)中

function enqueueUpdate(fiber, update) {
 var alternate = fiber.alternate;
 // 如果alternat為空并且更新隊(duì)列為空則創(chuàng)建更新隊(duì)列
 if (null === alternate) {
 var queue1 = fiber.updateQueue;
 var queue2 = null;
 null === queue1 &&
 (queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState));
 } else

 (queue1 = fiber.updateQueue),
 (queue2 = alternate.updateQueue),
 null === queue1
 ? null === queue2
  ? ((queue1 = fiber.updateQueue = createUpdateQueue(
  fiber.memoizedState
  )),
  (queue2 = alternate.updateQueue = createUpdateQueue(
  alternate.memoizedState
  )))
  : (queue1 = fiber.updateQueue = cloneUpdateQueue(queue2))
 : null === queue2 &&
  (queue2 = alternate.updateQueue = cloneUpdateQueue(queue1));
 null === queue2 || queue1 === queue2
 ? appendUpdateToQueue(queue1, update)
 : null === queue1.lastUpdate || null === queue2.lastUpdate
 ? (appendUpdateToQueue(queue1, update),
 appendUpdateToQueue(queue2, update))
 : (appendUpdateToQueue(queue1, update), (queue2.lastUpdate = update));
}

我們看scheduleWork下

function scheduleWork(fiber, expirationTime) {
 // 獲取根 node
 var root = scheduleWorkToRoot(fiber, expirationTime);
 null !== root &&
 (!isWorking &&
 0 !== nextRenderExpirationTime &&
 expirationTime < nextRenderExpirationTime &&
 ((interruptedBy = fiber), resetStack()),
 markPendingPriorityLevel(root, expirationTime),
 (isWorking && !isCommitting$1 && nextRoot === root) ||
 requestWork(root, root.expirationTime),
 nestedUpdateCount > NESTED_UPDATE_LIMIT &&
 ((nestedUpdateCount = 0), reactProdInvariant("185")));
}
function requestWork(root, expirationTime) {
 // 將需要渲染的root進(jìn)行記錄
 addRootToSchedule(root, expirationTime);
 if (isRendering) {
 // Prevent reentrancy. Remaining work will be scheduled at the end of
 // the currently rendering batch.
 return;
 }

 if (isBatchingUpdates) {
 // Flush work at the end of the batch.
 if (isUnbatchingUpdates) {
 // ...unless we're inside unbatchedUpdates, in which case we should
 // flush it now.
 nextFlushedRoot = root;
 nextFlushedExpirationTime = Sync;
 performWorkOnRoot(root, Sync, true);
 }
 // 執(zhí)行到這邊直接return,此時(shí)setState()這個(gè)過(guò)程已經(jīng)結(jié)束
 return;
 }

 // TODO: Get rid of Sync and use current time?
 if (expirationTime === Sync) {
 performSyncWork();
 } else {
 scheduleCallbackWithExpirationTime(root, expirationTime);
 }
}

太過(guò)復(fù)雜,一些方法其實(shí)還沒(méi)有看懂,但是根據(jù)斷點(diǎn)可以把執(zhí)行順序先理一下,在 setState 之后會(huì)執(zhí)行 performSyncWork ,隨后是如下的一個(gè)執(zhí)行順序

performSyncWork => performWorkOnRoot => renderRoot => workLoop => performUnitOfWork => beginWork => applyDerivedStateFromProps

最終方法是執(zhí)行

function applyDerivedStateFromProps(
 workInProgress,
 ctor,
 getDerivedStateFromProps,
 nextProps
) {
 var prevState = workInProgress.memoizedState;
 {
 if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) {
  // Invoke the function an extra time to help detect side-effects.
  getDerivedStateFromProps(nextProps, prevState);
 }
 }
 // 獲取改變的state
 var partialState = getDerivedStateFromProps(nextProps, prevState);
 {
 // 對(duì)一些錯(cuò)誤格式進(jìn)行警告
 warnOnUndefinedDerivedState(ctor, partialState);
 } // Merge the partial state and the previous state.
 // 判斷getDerivedStateFromProps返回的格式是否為空,如果不為空則將由原的state和它的返回值合并
 var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
 // 設(shè)置state
 // 一旦更新隊(duì)列為空,將派生狀態(tài)保留在基礎(chǔ)狀態(tài)當(dāng)中
 workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the
 // base state.
 var updateQueue = workInProgress.updateQueue;

 if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
 updateQueue.baseState = memoizedState;
 }
}

Vue

vue監(jiān)聽(tīng)變量變化依靠的是 watch ,因此我們先從源碼中看看, watch 是在哪里觸發(fā)的。

Watch觸發(fā)條件

在 src/core/instance 中有 initState()

/core/instance/state.js

在數(shù)據(jù)初始化時(shí) initData() ,會(huì)將每vue的data注冊(cè)到 objerserver 中

function initData (vm: Component) {
 // ...省略部分代碼
 
 // observe data
 observe(data, true /* asRootData */)
}
/**
 * Attempt to create an observer instance for a value,
 * returns the new observer if successfully observed,
 * or the existing observer if the value already has one.
 */
export function observe (value: any, asRootData: ?boolean): Observer | void {
 if (!isObject(value) || value instanceof VNode) {
 return
 }
 let ob: Observer | void
 if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
 ob = value.__ob__
 } else if (
 shouldObserve &&
 !isServerRendering() &&
 (Array.isArray(value) || isPlainObject(value)) &&
 Object.isExtensible(value) &&
 !value._isVue
 ) {
 // 創(chuàng)建observer
 ob = new Observer(value)
 }
 if (asRootData && ob) {
 ob.vmCount++
 }
 return ob
}

來(lái)看下 observer 的構(gòu)造方法,不管是array還是obj,他們最終都會(huì)調(diào)用的是 this.walk()

constructor (value: any) {
 this.value = value
 this.dep = new Dep()
 this.vmCount = 0
 def(value, '__ob__', this)
 if (Array.isArray(value)) {
 const augment = hasProto
 ? protoAugment
 : copyAugment
 augment(value, arrayMethods, arrayKeys)
 // 遍歷array中的每個(gè)值,然后調(diào)用walk
 this.observeArray(value)
 } else {
 this.walk(value)
 }
 }

我們?cè)賮?lái)看下walk方法,walk方法就是將object中的執(zhí)行 defineReactive() 方法,而這個(gè)方法實(shí)際就是改寫(xiě) set 和 get 方法

/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
walk (obj: Object) {
 const keys = Object.keys(obj)
 for (let i = 0; i < keys.length; i++) {
 defineReactive(obj, keys[i])
 }
}
/core/observer/index.js 
defineReactive 方法最為核心,它將set和get方法改寫(xiě),如果我們重新對(duì)變量進(jìn)行賦值,那么會(huì)判斷變量的新值是否等于舊值,如果不相等,則會(huì)觸發(fā) dep.notify() 從而回調(diào)watch中的方法。
/**
 * Define a reactive property on an Object.
 */
export function defineReactive (
 obj: Object,
 key: string,
 val: any,
 customSetter?: ?Function,
 shallow?: boolean
) {
 // dep當(dāng)中存放的是watcher數(shù)組 
 const dep = new Dep()
 const property = Object.getOwnPropertyDescriptor(obj, key)
 if (property && property.configurable === false) {
 return
 }
 // cater for pre-defined getter/setters
 const getter = property && property.get
 const setter = property && property.set
 if ((!getter || setter) && arguments.length === 2) { 
 // 如果第三個(gè)值沒(méi)有傳。那么val就直接從obj中根據(jù)key的值獲取
 val = obj[key]
 }
 let childOb = !shallow && observe(val)
 Object.defineProperty(obj, key, {
 enumerable: true,
 // 可設(shè)置值
 configurable: true,
 get: function reactiveGetter () {
 const value = getter ? getter.call(obj) : val
 if (Dep.target) {
 // dep中生成個(gè)watcher
 dep.depend()
 if (childOb) {
  childOb.dep.depend()
  if (Array.isArray(value)) {
  dependArray(value)
  }
 }
 }
 return value
 },
 // 重點(diǎn)看set方法
 set: function reactiveSetter (newVal) {
 // 獲取變量原始值
 const value = getter ? getter.call(obj) : val
 /* eslint-disable no-self-compare */
 // 進(jìn)行重復(fù)值比較 如果相等直接return
 if (newVal === value || (newVal !== newVal && value !== value)) {
 return
 }
 /* eslint-enable no-self-compare */
 if (process.env.NODE_ENV !== 'production' && customSetter) {
 // dev環(huán)境可以直接自定義set
 customSetter()
 }
 // 將新的值賦值
 if (setter) {
 setter.call(obj, newVal)
 } else {
 val = newVal
 }
 childOb = !shallow && observe(newVal)
 // 觸發(fā)watch事件
 // dep當(dāng)中是一個(gè)wacher的數(shù)組
 // notify會(huì)執(zhí)行wacher數(shù)組的update方法,update方法觸發(fā)最終的watcher的run方法,觸發(fā)watch回調(diào)
 dep.notify()
 }
 })
}

小程序

自定義Watch

小程序的data本身是不支持watch的,但是我們可以自行添加,我們參照 Vue 的寫(xiě)法自己寫(xiě)一個(gè)。

watcher.js

export function defineReactive (obj, key, callbackObj, val) {
 const property = Object.getOwnPropertyDescriptor(obj, key);
 console.log(property);
 const getter = property && property.get;
 const setter = property && property.set;
 val = obj[key]
 const callback = callbackObj[key];
 Object.defineProperty(obj, key, {
 enumerable: true,
 get: function reactiveGetter () {
 const value = getter ? getter.call(obj) : val
 return value
 },
 set: (newVal) => {
 console.log('start set');
 const value = getter ? getter.call(obj) : val
 if (typeof callback === 'function') {
 callback(newVal, val);
 }
 if (setter) {
 setter.call(obj, newVal)
 } else {
 val = newVal
 }
 console.log('finish set', newVal);
 }
 });
}
export function watch(cxt, callbackObj) {
 const data = cxt.data
 for (const key in data) {
 console.log(key);
 defineReactive(data, key, callbackObj)
 }
}

使用

我們?cè)趫?zhí)行watch回調(diào)前沒(méi)有對(duì)新老賦值進(jìn)行比較,原因是微信當(dāng)中對(duì)data中的變量賦值,即使給引用變量賦值還是相同的值,也會(huì)因?yàn)橐玫刂凡煌?,判斷不相等。如果想?duì)新老值進(jìn)行比較就不能使用 === ,可以先對(duì)obj或者array轉(zhuǎn)換為json字符串再比較。

//index.js
//獲取應(yīng)用實(shí)例
const app = getApp()
import {watch} from '../../utils/watcher';
Page({
 data: {
 motto: 'hello world',
 userInfo: {},
 hasUserInfo: false,
 canIUse: wx.canIUse('button.open-type.getUserInfo'),
 tableData: []
 },
 onLoad: function () {
 this.initWatcher();
 },
 initWatcher () {
 watch(this, {
 motto(newVal, oldVal) {
 console.log('newVal', newVal, 'oldVal', oldVal);
 },

 userInfo(newVal, oldVal) {
 console.log('newVal', newVal, 'oldVal', oldVal);
 },

 tableData(newVal, oldVal) {
 console.log('newVal', newVal, 'oldVal', oldVal);
 }
 }); 
 },
 onClickChangeStringData() {
 this.setData({
 motto: 'hello'
 });
 },
 onClickChangeObjData() {
 this.setData({
 userInfo: {
 name: 'helo'
 }
 });
 },
 onClickChangeArrayDataA() {
 const tableData = [];
 this.setData({
 tableData
 });
 }
})

參考

如何閱讀React源碼

React 16.3 ~ React 16.5 一些比較重要的改動(dòng)

總結(jié)

以上所述是小編給大家介紹的React和Vue中監(jiān)聽(tīng)變量變化的方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

  • 帶你了解前端的幾種包管理器(npm/pnpm等)

    帶你了解前端的幾種包管理器(npm/pnpm等)

    隨著前端工程化的應(yīng)用越來(lái)越廣,插件和包的管理也逐漸衍生出很多的管理器,常見(jiàn)的幾種包管理器如:npm、cnpm、yarn、pnpm,那你知道這些管理器之間有哪些區(qū)別嗎?我們一起來(lái)逐個(gè)認(rèn)識(shí)下它們
    2023-04-04
  • ant-design-vue 實(shí)現(xiàn)表格內(nèi)部字段驗(yàn)證功能

    ant-design-vue 實(shí)現(xiàn)表格內(nèi)部字段驗(yàn)證功能

    這篇文章主要介紹了ant-design-vue 實(shí)現(xiàn)表格內(nèi)部字段驗(yàn)證功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-12-12
  • vue開(kāi)發(fā)公共組件之返回頂部

    vue開(kāi)發(fā)公共組件之返回頂部

    這篇文章主要為大家詳細(xì)介紹了vue開(kāi)發(fā)公共組件之返回頂部,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • Vue初始化中的選項(xiàng)合并之initInternalComponent詳解

    Vue初始化中的選項(xiàng)合并之initInternalComponent詳解

    這篇文章主要介紹了Vue初始化中的選項(xiàng)合并之initInternalComponent的相關(guān)知識(shí),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-06-06
  • Vue解決跨域問(wèn)題常見(jiàn)方法詳解

    Vue解決跨域問(wèn)題常見(jiàn)方法詳解

    這篇文章主要介紹了Vue解決跨域問(wèn)題常見(jiàn)方法,結(jié)合實(shí)例形式詳細(xì)分析了vue出現(xiàn)跨域問(wèn)題的原因,以及常見(jiàn)解決方案與相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2023-06-06
  • 解決vuex數(shù)據(jù)異步造成初始化的時(shí)候沒(méi)值報(bào)錯(cuò)問(wèn)題

    解決vuex數(shù)據(jù)異步造成初始化的時(shí)候沒(méi)值報(bào)錯(cuò)問(wèn)題

    今天小編大家分享一篇解決vuex數(shù)據(jù)異步造成初始化的時(shí)候沒(méi)值報(bào)錯(cuò)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-11-11
  • vue項(xiàng)目中向數(shù)組添加元素的3種方式

    vue項(xiàng)目中向數(shù)組添加元素的3種方式

    這篇文章主要給大家介紹了關(guān)于vue項(xiàng)目中向數(shù)組添加元素的3種方式,在Vue中添加元素到數(shù)組非常簡(jiǎn)單,文中通過(guò)代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用vue具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-10-10
  • 解決vue2中使用axios http請(qǐng)求出現(xiàn)的問(wèn)題

    解決vue2中使用axios http請(qǐng)求出現(xiàn)的問(wèn)題

    下面小編就為大家分享一篇解決vue2中使用axios http請(qǐng)求出現(xiàn)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-03-03
  • el-table表格排序(多列排序和遠(yuǎn)程排序)

    el-table表格排序(多列排序和遠(yuǎn)程排序)

    本文主要介紹了el-table表格排序(多列排序和遠(yuǎn)程排序),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05
  • 在Vue3中生成動(dòng)態(tài)的word文檔的示例代碼

    在Vue3中生成動(dòng)態(tài)的word文檔的示例代碼

    這篇文章主要介紹了如何在 Vue 3 中生成動(dòng)態(tài)的 Word 文檔,在開(kāi)發(fā)過(guò)程中遇到一個(gè)需求,動(dòng)態(tài)生成一個(gè)word報(bào)表,當(dāng)時(shí)考慮了是前端做還是后端做的問(wèn)題,最后發(fā)現(xiàn)兩個(gè)解決需求的方法都大差不差,但考慮到前端少發(fā)一個(gè)請(qǐng)求,就此使用的前端來(lái)解決,需要的朋友可以參考下
    2024-09-09

最新評(píng)論