成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

ReactV16.3,即將更改的生命周期

wendux / 744人閱讀

摘要:我們目前的計(jì)劃是為不安全生命周期引入別名,和。從現(xiàn)在開始,只有新的生命周期名稱將起作用。從版本開始,更新以響應(yīng)更改的推薦方法是使用新的靜態(tài)生命周期。

注釋:本文是根據(jù)React的官方博客翻譯而成(文章地址:https://reactjs.org/blog/2018...)。
主要講述了React之后的更新方向,以及對(duì)之前生命周期所出現(xiàn)的問題的總結(jié),之后的React將逐步棄用一些生命周期和增加一些更實(shí)用更符合實(shí)際情況的生命周期。其中也為從傳統(tǒng)的生命周期遷移到新版本的React提出了一些解決方法。

一年多來,React團(tuán)隊(duì)一直致力于實(shí)現(xiàn)異步渲染。上個(gè)月,他在JSConf冰島的演講中,丹揭示了一些令人興奮的新的異步渲染可能性。現(xiàn)在,我們希望與您分享我們?cè)趯W(xué)習(xí)這些功能時(shí)學(xué)到的一些經(jīng)驗(yàn)教訓(xùn),以及一些幫助您準(zhǔn)備組件以在啟動(dòng)時(shí)進(jìn)行異步渲染的方法。

我們了解到的最大問題之一是,我們的一些傳統(tǒng)組件生命周期會(huì)導(dǎo)致一些不安全的編碼實(shí)踐。他們是:

componentWillMount

componentWillReceiveProps

componentWillUpdate

這些生命周期方法經(jīng)常被誤解和濫用;此外,我們預(yù)計(jì)他們的潛在濫用可能在異步渲染方面有更大的問題。因此,我們將在即將發(fā)布的版本中為這些生命周期添加一個(gè)“UNSAFE_”前綴。 (這里,“不安全”不是指安全性,而是表示使用這些生命周期的代碼將更有可能在未來的React版本中存在缺陷,特別是一旦啟用了異步渲染)。

[](https://reactjs.org/#gradual-...

React遵循語義版本控制, 所以這種改變將是漸進(jìn)的。我們目前的計(jì)劃是:

16.3:為不安全生命周期引入別名UNSAFE_componentWillMount,UNSAFE_componentWillReceiveProps和UNSAFE_componentWillUpdate。 (舊的生命周期名稱和新的別名都可以在此版本中使用。)

未來的16.x版本:為componentWillMount,componentWillReceiveProps和componentWillUpdate啟用棄用警告。 (舊的生命周期名稱和新的別名都可以在此版本中使用,但舊名稱會(huì)記錄DEV模式警告。)

17.0:刪除componentWillMount,componentWillReceiveProps和componentWillUpdate。 (從現(xiàn)在開始,只有新的“UNSAFE_”生命周期名稱將起作用。)

請(qǐng)注意,如果您是React應(yīng)用程序開發(fā)人員,那么您不必對(duì)遺留方法進(jìn)行任何操作。即將發(fā)布的16.3版本的主要目的是讓開源項(xiàng)目維護(hù)人員在任何棄用警告之前更新其庫。這些警告將在未來的16.x版本發(fā)布之前不會(huì)啟用。

我們?cè)贔acebook上維護(hù)了超過50,000個(gè)React組件,我們不打算立即重寫它們。我們知道遷移需要時(shí)間。我們將采用逐步遷移路徑以及React社區(qū)中的所有人。

從傳統(tǒng)生命周期遷移

如果您想開始使用React 16.3中引入的新組件API(或者如果您是維護(hù)人員提前更新庫),以下是一些示例,我們希望這些示例可以幫助您開始考慮組件的變化。隨著時(shí)間的推移,我們計(jì)劃在文檔中添加額外的“配方”,以展示如何以避免有問題的生命周期的方式執(zhí)行常見任務(wù)。

在開始之前,我們將簡(jiǎn)要概述為16.3版計(jì)劃的生命周期更改:

We are adding the following lifecycle aliases: UNSAFE_componentWillMount, UNSAFE_componentWillReceiveProps, and UNSAFE_componentWillUpdate. (Both the old lifecycle names and the new aliases will be supported.)

We are introducing two new lifecycles, static getDerivedStateFromProps and getSnapshotBeforeUpdate.

我們正在添加以下生命周期別名

(1) UNSAFE_componentWillMount,

(2) UNSAFE_componentWillReceiveProps

(3) UNSAFE_componentWillUpdate。 (舊的生命周期名稱和新的別名都將受支持。)

我們介紹了兩個(gè)新的生命周期,分別是getDerivedStateFromProps和getSnapshotBeforeUpdate。

新的生命周期: getDerivedStateFromProps
class Example extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    // ...
  }
}

新的靜態(tài)getDerivedStateFromProps生命周期在組件實(shí)例化以及接收新props后調(diào)用。它可以返回一個(gè)對(duì)象來更新state,或者返回null來表示新的props不需要任何state更新。

componentDidUpdate一起,這個(gè)新的生命周期應(yīng)該覆蓋傳統(tǒng)componentWillReceiveProps的所有用例。

新的生命周期: getSnapshotBeforeUpdate
class Example extends React.Component {
  getSnapshotBeforeUpdate(prevProps, prevState) {
    // ...
  }
}

新的getSnapshotBeforeUpdate生命周期在更新之前被調(diào)用(例如,在DOM被更新之前)。此生命周期的返回值將作為第三個(gè)參數(shù)傳遞給componentDidUpdate。 (這個(gè)生命周期不是經(jīng)常需要的,但可以用于在恢復(fù)期間手動(dòng)保存滾動(dòng)位置的情況。)

componentDidUpdate一起,這個(gè)新的生命周期將覆蓋舊版componentWillUpdate的所有用例。

You can find their type signatures in this gist.

我們看看如何在使用這兩種生命周期的,例子如下:

例如:

Initializing state(初始化狀態(tài))

Fetching external data(獲取外部數(shù)據(jù))

Adding event listeners (or subscriptions)(添加事件監(jiān)聽)

Updating state based on props(基于props更新state

Invoking external callbacks(調(diào)用外部的callbacks)

Side effects on props change

Fetching external data when props change(props改變時(shí)獲取外部數(shù)據(jù))

Reading DOM properties before an update(在更新之前讀取DOM屬性)

注意

為簡(jiǎn)潔起見,下面的示例是使用實(shí)驗(yàn)類屬性轉(zhuǎn)換編寫的,但如果沒有它,則應(yīng)用相同的遷移策略。

初始化狀態(tài):

這個(gè)例子展示了一個(gè)調(diào)用componentWillMount中帶有setState的組件:

// Before
class ExampleComponent extends React.Component {
  state = {};

  componentWillMount() {
    this.setState({
      currentColor: this.props.defaultColor,
      palette: "rgb",
    });
  }
}

這種類型的組件最簡(jiǎn)單的重構(gòu)是將狀態(tài)初始化移動(dòng)到構(gòu)造函數(shù)或?qū)傩猿跏贾翟O(shè)定項(xiàng),如下所示:

// After
class ExampleComponent extends React.Component {
  state = {
    currentColor: this.props.defaultColor,
    palette: "rgb",
  };
}
獲取外部數(shù)據(jù)

以下是使用componentWillMount獲取外部數(shù)據(jù)的組件示例:

// Before
class ExampleComponent extends React.Component {
  state = {
    externalData: null,
  };

  componentWillMount() {
    this._asyncRequest = asyncLoadData().then(
      externalData => {
        this._asyncRequest = null;
        this.setState({externalData});
      }
    );
  }

  componentWillUnmount() {
    if (this._asyncRequest) {
      this._asyncRequest.cancel();
    }
  }

  render() {
    if (this.state.externalData === null) {
      // Render loading state ...
    } else {
      // Render real UI ...
    }
  }
}

上述代碼對(duì)于服務(wù)器呈現(xiàn)(其中不使用外部數(shù)據(jù)的地方)和即將到來的異步呈現(xiàn)模式(其中請(qǐng)求可能被多次啟動(dòng))是有問題的。

對(duì)于大多數(shù)用例,建議的升級(jí)路徑是將數(shù)據(jù)提取移入componentDidMount

// After
class ExampleComponent extends React.Component {
  state = {
    externalData: null,
  };

  componentDidMount() {
    this._asyncRequest = asyncLoadData().then(
      externalData => {
        this._asyncRequest = null;
        this.setState({externalData});
      }
    );
  }

  componentWillUnmount() {
    if (this._asyncRequest) {
      this._asyncRequest.cancel();
    }
  }

  render() {
    if (this.state.externalData === null) {
      // Render loading state ...
    } else {
      // Render real UI ...
    }
  }
}

有一個(gè)常見的錯(cuò)誤觀念認(rèn)為,在componentWillMount中提取可以避免第一個(gè)空的渲染。在實(shí)踐中,這從來都不是真的,因?yàn)镽eact總是在componentWillMount之后立即執(zhí)行渲染。如果數(shù)據(jù)在componentWillMount觸發(fā)的時(shí)間內(nèi)不可用,則無論你在哪里提取數(shù)據(jù),第一個(gè)渲染仍將顯示加載狀態(tài)。這就是為什么在絕大多數(shù)情況下將提取移到componentDidMount沒有明顯效果。

注意:
一些高級(jí)用例(例如,像Relay這樣的庫)可能想要嘗試使用熱切的預(yù)取異步數(shù)據(jù)。在這里可以找到一個(gè)這樣做的例子。

從長(zhǎng)遠(yuǎn)來看,在React組件中獲取數(shù)據(jù)的規(guī)范方式可能基于JSConf冰島推出的“懸念”API。簡(jiǎn)單的數(shù)據(jù)提取解決方案以及像Apollo和Relay這樣的庫都可以在后臺(tái)使用。它比上述任一解決方案的冗余性都要小得多,但不會(huì)在16.3版本中及時(shí)完成。

當(dāng)支持服務(wù)器渲染時(shí),目前需要同步提供數(shù)據(jù) - componentWillMount通常用于此目的,但構(gòu)造函數(shù)可以用作替換。即將到來的懸念A(yù)PI將使得異步數(shù)據(jù)在客戶端和服務(wù)器呈現(xiàn)中都可以清晰地獲取。

添加時(shí)間監(jiān)聽

下面是一個(gè)在安裝時(shí)監(jiān)聽外部事件調(diào)度程序的組件示例:

// Before
class ExampleComponent extends React.Component {
  componentWillMount() {
    this.setState({
      subscribedValue: this.props.dataSource.value,
    });

    // This is not safe; it can leak!
    this.props.dataSource.subscribe(
      this.handleSubscriptionChange
    );
  }

  componentWillUnmount() {
    this.props.dataSource.unsubscribe(
      this.handleSubscriptionChange
    );
  }

  handleSubscriptionChange = dataSource => {
    this.setState({
      subscribedValue: dataSource.value,
    });
  };
}

不幸的是,這會(huì)導(dǎo)致服務(wù)器渲染(componentWillUnmount永遠(yuǎn)不會(huì)被調(diào)用)和異步渲染(在渲染完成之前渲染可能被中斷,導(dǎo)致componentWillUnmount不被調(diào)用)的內(nèi)存泄漏。

人們經(jīng)常認(rèn)為componentWillMountcomponentWillUnmount總是配對(duì),但這并不能保證。只有調(diào)用componentDidMount后,React才能保證稍后調(diào)用componentWillUnmount進(jìn)行清理。

出于這個(gè)原因,添加事件監(jiān)聽的推薦方式是使用componentDidMount生命周期:

// After
class ExampleComponent extends React.Component {
  state = {
    subscribedValue: this.props.dataSource.value,
  };

  componentDidMount() {
    // Event listeners are only safe to add after mount,
    // So they won"t leak if mount is interrupted or errors.
    this.props.dataSource.subscribe(
      this.handleSubscriptionChange
    );

    // External values could change between render and mount,
    // In some cases it may be important to handle this case.
    if (
      this.state.subscribedValue !==
      this.props.dataSource.value
    ) {
      this.setState({
        subscribedValue: this.props.dataSource.value,
      });
    }
  }

  componentWillUnmount() {
    this.props.dataSource.unsubscribe(
      this.handleSubscriptionChange
    );
  }

  handleSubscriptionChange = dataSource => {
    this.setState({
      subscribedValue: dataSource.value,
    });
  };
}

有時(shí)候更新監(jiān)聽以響應(yīng)屬性變化很重要。如果您使用的是像Redux或MobX這樣的庫,庫的容器組件會(huì)為您處理。對(duì)于應(yīng)用程序作者,我們創(chuàng)建了一個(gè)小型庫create-subscription來幫助解決這個(gè)問題。我們會(huì)將它與React 16.3一起發(fā)布。

Rather than passing a subscribable dataSource prop as we did in the example above, we could use create-subscription to pass in the subscribed value:

我們可以使用create-subscription來傳遞監(jiān)聽的值,而不是像上例那樣傳遞監(jiān)聽 的dataSource prop。

import {createSubscription} from "create-subscription";

const Subscription = createSubscription({
  getCurrentValue(sourceProp) {
    // Return the current value of the subscription (sourceProp).
    return sourceProp.value;
  },

  subscribe(sourceProp, callback) {
    function handleSubscriptionChange() {
      callback(sourceProp.value);
    }

    // Subscribe (e.g. add an event listener) to the subscription (sourceProp).
    // Call callback(newValue) whenever a subscription changes.
    sourceProp.subscribe(handleSubscriptionChange);

    // Return an unsubscribe method.
    return function unsubscribe() {
      sourceProp.unsubscribe(handleSubscriptionChange);
    };
  },
});

// Rather than passing the subscribable source to our ExampleComponent,
// We could just pass the subscribed value directly:
``
  {value => ``}
``;
注意>>像Relay / Apollo這樣的庫應(yīng)該使用與創(chuàng)建訂閱相同的技術(shù)手動(dòng)管理訂閱(如此處所引用的),并采用最適合其庫使用的優(yōu)化方式。
基于props更新state

以下是使用舊版componentWillReceiveProps生命周期基于新的道具值更新狀態(tài)的組件示例:

// Before
class ExampleComponent extends React.Component {
  state = {
    isScrollingDown: false,
  };

  componentWillReceiveProps(nextProps) {
    if (this.props.currentRow !== nextProps.currentRow) {
      this.setState({
        isScrollingDown:
          nextProps.currentRow > this.props.currentRow,
      });
    }
  }
}

盡管上面的代碼本身并沒有問題,但componentWillReceiveProps生命周期通常會(huì)被錯(cuò)誤地用于解決問題。因此,該方法將被棄用。

從版本16.3開始,更新state以響應(yīng)props更改的推薦方法是使用新的靜態(tài)getDerivedStateFromProps生命周期。 (生命周期在組件創(chuàng)建時(shí)以及每次收到新道具時(shí)調(diào)用):

// After
class ExampleComponent extends React.Component {
  // Initialize state in constructor,
  // Or with a property initializer.
  state = {
    isScrollingDown: false,
    lastRow: null,
  };

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.currentRow !== prevState.lastRow) {
      return {
        isScrollingDown:
          nextProps.currentRow > prevState.lastRow,
        lastRow: nextProps.currentRow,
      };
    }

    // Return null to indicate no change to state.
    return null;
  }
}

You may notice in the example above that props.currentRow is mirrored in state (as state.lastRow). This enables getDerivedStateFromProps to access the previous props value in the same way as is done in componentWillReceiveProps.

你可能會(huì)注意到在上面的例子中,props.currentRow是一個(gè)鏡像狀態(tài)(如state.lastRow)。這使得getDerivedStateFromProps可以像在componentWillReceiveProps中一樣訪問以前的props值。

您可能想知道為什么我們不只是將先前的props作為參數(shù)傳遞給getDerivedStateFromProps。我們?cè)谠O(shè)計(jì)API時(shí)考慮了這個(gè)選項(xiàng),但最終決定反對(duì)它,原因有兩個(gè):

A prevProps parameter would be null the first time getDerivedStateFromProps was called (after instantiation), requiring an if-not-null check to be added any time prevProps was accessed.

Not passing the previous props to this function is a step toward freeing up memory in future versions of React. (If React does not need to pass previous props to lifecycles, then it does not need to keep the previous props object in memory.)

在第一次調(diào)用getDerivedStateFromProps(實(shí)例化后)時(shí),prevProps參數(shù)將為null,需要在訪問prevProps時(shí)添加if-not-null檢查。

沒有將以前的props傳遞給這個(gè)函數(shù),在未來版本的React中釋放內(nèi)存的一個(gè)步驟。 (如果React不需要將先前的道具傳遞給生命周期,那么它不需要將先前的道具對(duì)象保留在內(nèi)存中。)

注意:如果您正在編寫共享組件,那么react-lifecycles-compat polyfill可以使新的getDerivedStateFromProps生命周期與舊版本的React一起使用。詳細(xì)了解如何在下面使用它。
調(diào)用外部回調(diào)函數(shù)

下面是一個(gè)在內(nèi)部狀態(tài)發(fā)生變化時(shí)調(diào)用外部函數(shù)的組件示例:

// Before
class ExampleComponent extends React.Component {
  componentWillUpdate(nextProps, nextState) {
    if (
      this.state.someStatefulValue !==
      nextState.someStatefulValue
    ) {
      nextProps.onChange(nextState.someStatefulValue);
    }
  }
}

在異步模式下使用componentWillUpdate都是不安全的,因?yàn)橥獠炕卣{(diào)可能會(huì)多次調(diào)用只更新一次。相反,應(yīng)該使用componentDidUpdate生命周期,因?yàn)樗WC每次更新只調(diào)用一次:

// After
class ExampleComponent extends React.Component {
  componentDidUpdate(prevProps, prevState) {
    if (
      this.state.someStatefulValue !==
      prevState.someStatefulValue
    ) {
      this.props.onChange(this.state.someStatefulValue);
    }
  }
}
props改變的副作用

與上述 事例類似,有時(shí)組件在道具更改時(shí)會(huì)產(chǎn)生副作用。

// Before
class ExampleComponent extends React.Component {
  componentWillReceiveProps(nextProps) {
    if (this.props.isVisible !== nextProps.isVisible) {
      logVisibleChange(nextProps.isVisible);
    }
  }
}

componentWillUpdate一樣,componentWillReceiveProps可能會(huì)多次調(diào)用但是只更新一次。出于這個(gè)原因,避免在此方法中導(dǎo)致的副作用非常重要。相反,應(yīng)該使用componentDidUpdate,因?yàn)樗WC每次更新只調(diào)用一次:

// After
class ExampleComponent extends React.Component {
  componentDidUpdate(prevProps, prevState) {
    if (this.props.isVisible !== prevProps.isVisible) {
      logVisibleChange(this.props.isVisible);
    }
  }
}
props改變時(shí)獲取外部數(shù)據(jù)

以下是根據(jù)propsvalues提取外部數(shù)據(jù)的組件示例:

// Before
class ExampleComponent extends React.Component {
  state = {
    externalData: null,
  };

  componentDidMount() {
    this._loadAsyncData(this.props.id);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.id !== this.props.id) {
      this.setState({externalData: null});
      this._loadAsyncData(nextProps.id);
    }
  }

  componentWillUnmount() {
    if (this._asyncRequest) {
      this._asyncRequest.cancel();
    }
  }

  render() {
    if (this.state.externalData === null) {
      // Render loading state ...
    } else {
      // Render real UI ...
    }
  }

  _loadAsyncData(id) {
    this._asyncRequest = asyncLoadData(id).then(
      externalData => {
        this._asyncRequest = null;
        this.setState({externalData});
      }
    );
  }
}

此組件的推薦升級(jí)路徑是將數(shù)據(jù)更新移動(dòng)到componentDidUpdate中。在渲染新道具之前,您還可以使用新的getDerivedStateFromProps生命周期清除陳舊的數(shù)據(jù):

// After
class ExampleComponent extends React.Component {
  state = {
    externalData: null,
  };

  static getDerivedStateFromProps(nextProps, prevState) {
    // Store prevId in state so we can compare when props change.
    // Clear out previously-loaded data (so we don"t render stale stuff).
    if (nextProps.id !== prevState.prevId) {
      return {
        externalData: null,
        prevId: nextProps.id,
      };
    }

    // No state update necessary
    return null;
  }

  componentDidMount() {
    this._loadAsyncData(this.props.id);
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.externalData === null) {
      this._loadAsyncData(this.props.id);
    }
  }

  componentWillUnmount() {
    if (this._asyncRequest) {
      this._asyncRequest.cancel();
    }
  }

  render() {
    if (this.state.externalData === null) {
      // Render loading state ...
    } else {
      // Render real UI ...
    }
  }

  _loadAsyncData(id) {
    this._asyncRequest = asyncLoadData(id).then(
      externalData => {
        this._asyncRequest = null;
        this.setState({externalData});
      }
    );
  }
}
注意>如果您使用支持取消的HTTP庫(如axios),那么卸載時(shí)取消正在進(jìn)行的請(qǐng)求很簡(jiǎn)單。對(duì)于原生Promise,您可以使用如下所示的方法。
在更新之前讀取DOM屬性

下面是一個(gè)組件的例子,它在更新之前從DOM中讀取屬性,以便在列表中保持滾動(dòng)位置:

class ScrollingList extends React.Component {
  listRef = null;
  previousScrollOffset = null;

  componentWillUpdate(nextProps, nextState) {
    // Are we adding new items to the list?
    // Capture the scroll position so we can adjust scroll later.
    if (this.props.list.length < nextProps.list.length) {
      this.previousScrollOffset =
        this.listRef.scrollHeight - this.listRef.scrollTop;
    }
  }

  componentDidUpdate(prevProps, prevState) {
    // If previousScrollOffset is set, we"ve just added new items.
    // Adjust scroll so these new items don"t push the old ones out of view.
    if (this.previousScrollOffset !== null) {
      this.listRef.scrollTop =
        this.listRef.scrollHeight -
        this.previousScrollOffset;
      this.previousScrollOffset = null;
    }
  }

  render() {
    return (
      `
` {/* ...contents... */} `
` ); } setListRef = ref => { this.listRef = ref; }; }

在上面的例子中,componentWillUpdate被用來讀取DOM屬性。但是,對(duì)于異步渲染,“render”階段生命周期(如componentWillUpdaterender)與“commit”階段生命周期(如componentDidUpdate)之間可能存在延遲。如果用戶在這段時(shí)間內(nèi)做了類似調(diào)整窗口大小的操作,則從componentWillUpdate中讀取的scrollHeight值將失效。

解決此問題的方法是使用新的“commit”階段生命周期getSnapshotBeforeUpdate。在數(shù)據(jù)發(fā)生變化之前立即調(diào)用該方法(例如,在更新DOM之前)。它可以將React的值作為參數(shù)傳遞給componentDidUpdate,在數(shù)據(jù)發(fā)生變化后立即調(diào)用它。

這兩個(gè)生命周期可以像這樣一起使用:

class ScrollingList extends React.Component {
  listRef = null;

  getSnapshotBeforeUpdate(prevProps, prevState) {
    // Are we adding new items to the list?
    // Capture the scroll position so we can adjust scroll later.
    if (prevProps.list.length < this.props.list.length) {
      return (
        this.listRef.scrollHeight - this.listRef.scrollTop
      );
    }
    return null;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // If we have a snapshot value, we"ve just added new items.
    // Adjust scroll so these new items don"t push the old ones out of view.
    // (snapshot here is the value returned from getSnapshotBeforeUpdate)
    if (snapshot !== null) {
      this.listRef.scrollTop =
        this.listRef.scrollHeight - snapshot;
    }
  }

  render() {
    return (
      `
` {/* ...contents... */} `
` ); } setListRef = ref => { this.listRef = ref; }; }
注意>>如果您正在編寫共享組件,那么react-lifecycles-compat polyfill可以使新的getSnapshotBeforeUpdate生命周期與舊版本的React一起使用。詳細(xì)了解如何使用它。
其它情況

While we tried to cover the most common use cases in this post, we recognize that we might have missed some of them. If you are using componentWillMount, componentWillUpdate, or componentWillReceiveProps in ways that aren’t covered by this blog post, and aren’t sure how to migrate off these legacy lifecycles, please file a new issue against our documentation with your code examples and as much background information as you can provide. We will update this document with new alternative patterns as they come up.

除了以上的一些常見的例子,還可能會(huì)有別的情況本篇文章沒有涵蓋到,如果您以本博文未涉及的方式使用componentWillMount,componentWillUpdatecomponentWillReceiveProps,并且不確定如何遷移這些傳統(tǒng)生命周期,你可以提供您的代碼示例和我們的文檔,并且一起提交一個(gè)新問題。我們將在更新這份文件時(shí)提供新的替代模式。

開源項(xiàng)目維護(hù)者

開源維護(hù)人員可能想知道這些更改對(duì)于共享組件意味著什么。如果實(shí)現(xiàn)上述建議,那么依賴于新的靜態(tài)getDerivedStateFromProps生命周期的組件會(huì)發(fā)生什么情況?你是否還必須發(fā)布一個(gè)新的主要版本,并降低React 16.2及更高版本的兼容性?

當(dāng)React 16.3發(fā)布時(shí),我們還將發(fā)布一個(gè)新的npm包, react-lifecycles-compat。該npm包會(huì)填充組件,以便新的getDerivedStateFromPropsgetSnapshotBeforeUpdate生命周期也可以與舊版本的React(0.14.9+)一起使用。

要使用這個(gè)polyfill,首先將它作為依賴項(xiàng)添加到您的庫中:

# Yarn
yarn add react-lifecycles-compat

# NPM
npm install react-lifecycles-compat --save

接下來,更新您的組件以使用新的生命周期(如上所述)。

最后,使用polyfill將組件向后兼容舊版本的React:

import React from "react";
import {polyfill} from "react-lifecycles-compat";

class ExampleComponent extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    // Your state update logic here ...
  }
}

// Polyfill your component to work with older versions of React:
polyfill(ExampleComponent);

export default ExampleComponent;

文章來源

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/94380.html

相關(guān)文章

  • 前端方便面

    摘要:技術(shù)前端布局推進(jìn)劑間距規(guī)范化利用變量實(shí)現(xiàn)令人震驚的懸浮效果很棒,但有些情況不適用布局說可能是最全的圖片版學(xué)習(xí)網(wǎng)格布局使用的九大誤區(qū)圖解布局布局揭秘和中新增功能探索版本迭代論基礎(chǔ)談?wù)雇麑?duì)比探究繪圖中撤銷功能的實(shí)現(xiàn)方式即將更改的生命周期幾道高 技術(shù) CSS 前端布局推進(jìn)劑 - 間距規(guī)范化 利用CSS變量實(shí)現(xiàn)令人震驚的懸浮效果 Flexbox 很棒,但有些情況不適用 CSS布局說——可能是最...

    liaoyg8023 評(píng)論0 收藏0
  • 前端方便面

    摘要:技術(shù)前端布局推進(jìn)劑間距規(guī)范化利用變量實(shí)現(xiàn)令人震驚的懸浮效果很棒,但有些情況不適用布局說可能是最全的圖片版學(xué)習(xí)網(wǎng)格布局使用的九大誤區(qū)圖解布局布局揭秘和中新增功能探索版本迭代論基礎(chǔ)談?wù)雇麑?duì)比探究繪圖中撤銷功能的實(shí)現(xiàn)方式即將更改的生命周期幾道高 技術(shù) CSS 前端布局推進(jìn)劑 - 間距規(guī)范化 利用CSS變量實(shí)現(xiàn)令人震驚的懸浮效果 Flexbox 很棒,但有些情況不適用 CSS布局說——可能是最...

    DevWiki 評(píng)論0 收藏0
  • react 生命周期

    摘要:一個(gè)組件的生命周期分為三個(gè)部分實(shí)例化存在期和銷毀時(shí)。如果回調(diào)函數(shù)以函數(shù)的方式來指定,那么在組件更新的時(shí)候回調(diào)會(huì)被調(diào)用次。 一個(gè)React組件的生命周期分為三個(gè)部分:實(shí)例化、存在期和銷毀時(shí)。 實(shí)例化階段 客戶端渲染時(shí),如下依次被調(diào)用 getDefaultProps() getInitialState() componentWillMount() render() component...

    Fundebug 評(píng)論0 收藏0
  • React組件生命周期詳解

    摘要:組件生命周期構(gòu)造方法是對(duì)類的默認(rèn)方法,通過命令生成對(duì)象實(shí)例時(shí)自動(dòng)調(diào)用該方法。該生命周期可以發(fā)起異步請(qǐng)求,并。后廢棄該生命周期,可以在中完成設(shè)置渲染組件是一個(gè)組件必須定義的生命周期,用來渲染。該生命周期內(nèi)可以進(jìn)行。 React組件生命周期 constructor( ) 構(gòu)造方法 constructor是ES6對(duì)類的默認(rèn)方法,通過 new 命令生成對(duì)象實(shí)例時(shí)自動(dòng)調(diào)用該方法。并且,該方法是...

    learn_shifeng 評(píng)論0 收藏0
  • React V16.3生命周期:The Component Lifecycle Flowchart

    摘要:學(xué)習(xí)免不了對(duì)組件生命周期的學(xué)習(xí),我們應(yīng)該掌握最新生命周期,學(xué)以致用,以達(dá)到性能優(yōu)化的目的。 學(xué)習(xí)React免不了對(duì)組件生命周期的學(xué)習(xí),我們應(yīng)該掌握最新生命周期,學(xué)以致用,以達(dá)到性能優(yōu)化的目的。 The Component Lifecycle React Version: 16.3 1 生命周期可視化 高清大圖--歡迎轉(zhuǎn)載 showImg(https://segmentfault.co...

    curried 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<