React 的 diff 算法(称为协调)使用组件标识来确定它是应该更新现有子树还是将其丢弃并挂载新子树。如果从 render 返回的组件与前一个渲染中的组件相同(===),则 React 通过将子树与新子树进行区分来递归更新子树。如果它们不相等,则完全卸载前一个子树。
例子:下面有两个计数器,第一个是正常组件,第二个是函数包裹的高阶组件,点第一个的时候第二个组件的状态会清空。
1  | function WidthWrapper (WrappedComponent) {  | 
重新挂载组件会导致该组件及其所有子组件的状态丢失。
解决上面的问题1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57function WidthWrapper (WrappedComponent) {
  return class extends React.Component {
    componentDidMount() {
      console.log('页面加载完成')
    }
    render() {
      return (
        <WrappedComponent />
      );
    }
  }
}
class Example extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      number: 0
    }
  }
  handleClick = () => {
    this.setState({number: this.state.number + 1})
  }
  render() {
    return (
      <>
        <div>{this.state.number}</div>
        <button onClick={this.handleClick}>+</button>
      </>
    )
  }
}
let MyComponent = WidthWrapper(Example) // 在组件之外创建
class App extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      number: 0
    }
  }
  handleClick = () => {
    this.setState({number: this.state.number + 1})
  }
  render() {
    return (
      <>
        <div>{this.state.number}</div>
        <button onClick={this.handleClick}>+</button>
        <MyComponent />
      </>
    )
  }
}
export default App;
如果在组件之外创建 HOC,这样一来组件只会创建一次。因此,每次 render 时都会是同一个组件。
1  | function WidthWrapper (WrappedComponent) {  | 
在极少数情况下,你需要动态调用HOC。你可以在组件的生命周期方法或其构造函数中进行调用。