React:组件的两个不同实例的 componentDidUpdate 是否相同?

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

我正在使用 react-router v4 编写一个 React (ES6, v16) (typescript) 应用程序。我正在观察一种非常奇怪的行为。这是我的渲染代码(非常简化):

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
    }
}

现在,当我在应用程序中单击 link“/foo/add”时,第一个 "Route" 组件中的处理程序被触发(如预期的那样)并且组件 "FormEntry" 已安装。 componentDidMount 方法被正确触发。

现在我点击link "foo/edit/1"。第二条路线的处理程序被解雇。

这一次,在 "FormEntry" 组件内部,生命周期方法 "componentDidMount" 没有被触发,方法 "componentDidUpdate" 被调用。但这显然是正在安装的 FormEntry 的不同 "instance"。我期待看到生命周期方法开始...

我的应用程序中似乎只有一个 "FormEntry" 实例。那么为什么在第二种情况下(当 url "foo/edit:id" 的路由处理程序时)这个实例没有通过所有生命周期方法??

它是 React v16 版本中的重大更改吗? (我在以前的 React 版本中没有观察到这种行为)。

非常感谢您的见解

<Switch>检查上一条匹配路由的JSX,并与下一条路由的新JSX进行比较。

如果匹配,它将使用它并且只更新更改的值而不重新安装组件。

否则它将创建新的反应元素并实例化新组件。

在此处查看: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>
}