国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

React和Vue中監聽變量變化的方法

2024-05-06 15:28:00
字體:
來源:轉載
供稿:網友

React 中

本地調試React代碼的方法

yarn build

場景

假設有這樣一個場景,父組件傳遞子組件一個A參數,子組件需要監聽A參數的變化轉換為state。

16之前

在React以前我們可以使用 componentWillReveiveProps 來監聽 props 的變換

16之后

在最新版本的React中可以使用新出的 getDerivedStateFromProps 進行props的監聽, getDerivedStateFromProps 可以返回 null 或者一個對象,如果是對象,則會更新 state

getDerivedStateFromProps觸發條件

我們的目標就是找到 getDerivedStateFromProps 的 觸發條件

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

setState 在 react.development.js 當中

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'); }}

執行的是一個警告方法

function warnNoop(publicInstance, callerName) { { // 實例的構造體 var _constructor = publicInstance.constructor; var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass'; // 組成一個key 組件名稱+方法名(列如setState) var warningKey = componentName + '.' + callerName; // 如果已經輸出過警告了就不會再輸出 if (didWarnStateUpdateForUnmountedComponent[warningKey]) { return; } // 在開發者工具的終端里輸出警告日志 不能直接使用 component.setState來調用  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; }}

看來 ReactNoopUpdateQueue 是一個抽象類,實際的方法并不是在這里實現的,同時我們看下最初 updater 賦值的地方,初始化 Component 時,會傳入實際的 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;}            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 滨州市| 吉林省| 通河县| 肥西县| 呼伦贝尔市| 仙桃市| 濮阳市| 三都| 龙泉市| 铜梁县| 鹤庆县| 东乌| 萍乡市| 朝阳市| 兰西县| 九寨沟县| 南华县| 瓮安县| 泰兴市| 大兴区| 涟源市| 蒙城县| 三穗县| 德钦县| 寻甸| 夏河县| 晋宁县| 大石桥市| 稷山县| 乌审旗| 江阴市| 萨嘎县| 分宜县| 原平市| 耒阳市| 丹寨县| 九寨沟县| 凤庆县| 拜城县| 绥德县| 洪雅县|