最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to count how many instances of a React component are mounted? - Stack Overflow

programmeradmin2浏览0评论

I've got an Ad component that is dynamically loaded into different pages across an eCommerce application. I'd like to be able to know how many of these components exist in a react page at any given time.

I'm wondering if there's a react pattern for determining how many instances of a component exist in a page at any given time.

I'd imagine you would do this in the root of the application, and iterate through react.children, counting the Ad components as they appear.

Does anyone know best practice for this approach?

Thanks :)

  match({ routes, location, history: browserHistory }, (error, renderProps) => {


    const requireComponents = (props) => props ? propsponents.map((component) =>
      component && component.requireComponent && store.dispatch(component.requireComponent())
    ) : [];

    const render = () => {
      store.initialRender = true;
      ReactDOM.hydrate(
        (
          <AnalyticsProvider onEvent={analyticsHandler}>
            <Provider store={store}>
              <Router history={browserHistory}>{routes}</Router>
            </Provider>
          </AnalyticsProvider>
        ),
        document.querySelector(".js-content")
      );
      store.initialRender = false;
    };

    Promise.all(requireComponents(renderProps))
      .then(render)
      .then(() => window.newrelic.addPageAction("FIT"));
  });

I've tried console.logging renderProps - and there are some routes in that object, and also a getComponent function but I haven't seen the results I"m looking for.

I've got an Ad component that is dynamically loaded into different pages across an eCommerce application. I'd like to be able to know how many of these components exist in a react page at any given time.

I'm wondering if there's a react pattern for determining how many instances of a component exist in a page at any given time.

I'd imagine you would do this in the root of the application, and iterate through react.children, counting the Ad components as they appear.

Does anyone know best practice for this approach?

Thanks :)

  match({ routes, location, history: browserHistory }, (error, renderProps) => {


    const requireComponents = (props) => props ? props.components.map((component) =>
      component && component.requireComponent && store.dispatch(component.requireComponent())
    ) : [];

    const render = () => {
      store.initialRender = true;
      ReactDOM.hydrate(
        (
          <AnalyticsProvider onEvent={analyticsHandler}>
            <Provider store={store}>
              <Router history={browserHistory}>{routes}</Router>
            </Provider>
          </AnalyticsProvider>
        ),
        document.querySelector(".js-content")
      );
      store.initialRender = false;
    };

    Promise.all(requireComponents(renderProps))
      .then(render)
      .then(() => window.newrelic.addPageAction("FIT"));
  });

I've tried console.logging renderProps - and there are some routes in that object, and also a getComponent function but I haven't seen the results I"m looking for.

Share Improve this question edited Aug 2, 2019 at 18:48 Matthieu Libeer 2,3651 gold badge13 silver badges18 bronze badges asked Aug 2, 2019 at 17:12 zero_coolzero_cool 4,2645 gold badges44 silver badges57 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 15

To count the number of mounted intances of a given component, you can add the following to your component (Ad.js in your case).

import React, { useEffect } from 'react'

let instancesCount = 0

const Ad = (props) => {
  useEffect(() => {
    instancesCount += 1
    console.log({instancesCount})
    return () => {
      instancesCount -= 1
      console.log({instancesCount})
    }
  }, [])

  return (
    // Whatever your component does
  )

This will increment instancesCount each time a instance of Ad is mounted to the DOM, and decrement it each time an instance is unmounted, effectively giving you the exact number of mounted instances at any given time. It will also log that number every time an instance is mounted or unmounted.

Requirement: React v > 16.8.0

If you have a lower version of React, or if your Ad component is a class component, use this:

let instancesCount = 0
class Ad extends React.Component {
  componentDidMount = () => {
    instancesCount += 1
    console.log({instancesCount})
  }
  componentWillUnmount = () => { 
    instancesCount -= 1
    console.log({instancesCount})
  }

  // Whatever your component does
}

One simple way to do this is just use the DOM to locate a common class on the component. You don't have to use the React API. So, if the component you are looking for has:

<div class="unique-component">
 ... rest of component
</div>

Just use:

document.querySelectorAll(".unique-component").length
发布评论

评论列表(0)

  1. 暂无评论