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));

现在,每次 props 发生任何变化时,控制台都会打印:
'wrapped component mounted'
'wrapper component mounted'

如果我删除 Wrapper ,它只会打印一次(安装时
在第一时间):
`wrapped component mounted`

那么,为什么在高阶组件中多次调用 componentDidMount 呢?

最佳答案

connect()(wrap(Wrapper));

我已经测试过了。它有效。

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。这是循环

关于javascript - 为什么在高阶组件中多次调用 componentDidMount?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38081726/

10-09 06:29