簡體   English   中英

React:componentDidUpdate對於組件的2個不同實例是否相同?

[英]React: is componentDidUpdate same for 2 different instances of a component?

我正在使用react-router v4編寫一個React(ES6,v16)(打字稿)應用程序。 我觀察到一種非常奇怪的行為。 這是我的渲染代碼(非常簡化):

render() {
   <Switch>

      <Route
         path="/foo/add"
         render={ props => {
                return (
                   <FormEntry title="add new" />
                );
         }}
      />

      <Route
         path="/foo/edit/:id"
         render={ props => {
                 return (
                    <FormEntry title="edit item" />
                 );
         }}
      />
   </Switch>
}

這是FormEntry組件(簡化):

class FormEntry extends React.Component< { title: string }, any > {
    render() {
       return (
          <div>
             {this.props.title}
          </div>
       );
    }

    componentDidMount() {
       // code goes here
    }

    componentDidUpdate() {
       // code goes here
    }
}

現在,當在應用程序內部單擊鏈接“/ foo / add”時,將觸發第一個“Route”組件中的處理程序(按預期方式)並安裝組件“FormEntry”。 正確觸發方法componentDidMount。

現在我點擊“foo / edit / 1”鏈接。 第二個Route的處理程序被觸發。

這次,在“FormEntry”組件內部,未觸發生命周期方法“componentDidMount”,調用方法“componentDidUpdate”。 但這是正在安裝的FormEntry的另一個“實例”。 我期待看到生命周期方法開始......

看起來我的應用程序中只有一個“FormEntry”實例。 那么為什么在第二種情況下(當URL處理程序為url“foo / edit:id”時)這個實例不會通過所有生命周期方法?

這是Re16的v16版本的重大變化嗎? (我在之前版本的反應中沒有觀察到這種行為)。

非常感謝您的見解

<Switch>檢查上一個匹配路由的JSX ,並將其與下一個路由的新JSX進行比較。

如果匹配,它將使用它並僅更新更改的值而無需重新安裝組件。

否則,它將創建新的react元素並實例化新的組件。

點擊此處: https//github.com/ReactTraining/react-router/pull/4592

轉向這是為了使用這樣的關鍵屬性:

render() {
   <Switch>

      <Route
         path="/foo/add"
         render={ props => {
                return (
                   <FormEntry key="1" title="add new" />
                );
         }}
      />

      <Route
         path="/foo/edit/:id"
         render={ props => {
                 return (
                    <FormEntry  key="2" title="edit item" />
                 );
         }}
      />
   </Switch>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM