为什么在更高阶组件中调用componentDidMount不止一次?

时间:2016-06-28 16:35:49

标签: javascript reactjs redux react-redux

docs说:

  

立即仅在客户端(不在服务器上)调用一次   初始渲染发生后。

现在,当我尝试创建更高阶的组件时:

import React from 'react';
import { connect } from 'react-redux';

function wrap(Wrapped) {

  class Wrapper extends React.Component {
    componentDidMount() {
      // I will place some reusable functionality here which need to
      // be called once on mounted.
      console.log('wrapper component mounted');
    }
    render() {
      return <Wrapped {...this.props}/>
    }
  }
  return Wrapper;
}

class Wrapped extends React.Component {
  componentDidMount() {
    console.log('wrapped component mounted');
  }
  render() {
    return <div></div>;
  }
}

connect()(wrap(Wrapped));

现在,每次在道具中发生任何变化时,控制台都会打印出来:

'wrapped component mounted'
'wrapper component mounted'

如果我删除Wrapper,它只打印一次(安装时) 在第一次):

`wrapped component mounted`

那么,为什么componentDidMount在更高阶的组件中不止一次被调用?

1 个答案:

答案 0 :(得分:1)

连接()(包裹物(包装)); &lt; - 替换为Wrapped

我测试了它。它有效。

function wrap(Wrapped) {
  class Wrapper extends React.Component {
    componentDidMount() {
      console.log('wrapper component mounted');
    }
    render() {
      return <Wrapped {...this.props}/>
    }
    componentDidUpdate(prevProps, prevState){
        console.log(this.props);
    }
  }
  return Wrapper;
}
class Wrapped extends React.Component {
  componentDidMount() {
    console.log('wrapped component mounted');
  }
  componentDidUpdate(prevProps, prevState){
      console.log(this.props);
  }
  render() {
    return <div></div>;
  }
}

connect(state=>({state}))(wrap(Wrapped));

wrap func返回Wrapper,你不能将Wrapper传递给wrap func。它的循环