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;}
新聞熱點
疑難解答
圖片精選