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

标签 javascript reactjs redux react-redux

docs说:

Invoked once, only on the client (not on the server), immediately after the initial rendering occurs.

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

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

现在,每次 Prop 发生变化时,控制台都会打印:

'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/

相关文章:

javascript - Node.JS 中的异步

javascript - 如何解决使用 SDK V4 模板在 C# 中开发的 Web Chat Bot 的 HTML 页面无法在 IE 11 浏览器中打开的问题?

javascript - 选择选项使用 JQUERY 通过文本获取值

javascript - React 表单不更新 mongo 数据库

reactjs - React Native 中的 Stomp 和 SockJs

javascript - 如何获取 overflow hidden 的div的高度?

javascript - React js - 测试组件时如何模拟上下文

reactjs - 无法读取未定义的属性(读取 'map')

javascript - Redux Prop 不起作用

javascript - 使用 React 和 Redux 的收藏夹购物车