Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

reactjs - What is the best way to keep track when all components rendered from a loop

Say we have a parent component rendering a ChildComponent from a loop with different props N number of times, how would you keep track of when they are all done rendering?

By done rendering I mean something similar to "componentDidMount"

        return keys.map((component) => {
            return sorted[component].length > 0 &&
                <Card key={component} articles={sorted[component]}
                      category={component}/>
        })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I assume by "done rendering" you mean the DOM has been updated to show the latest data. The code for that will be the same whether you've got an array of children, or just one child, or anything else, because until concurrent mode is a complete feature in react, all rendering is done synchronously.

For a class component, add a componentDidUpdate function. This will be called after rendering is complete, but not for the first render. If you need the first render too, then add componentDidMount also:

class Example extends React.Component {
  componentDidMount() {
    console.log('done rendering (1st time)');
  }

  componentDidUpdate() {
    console.log('done rendering (2+)');
  }

  render() {
    return keys.map((component) => {
      return sorted[component].length > 0 &&
        <Card key={component} articles={sorted[component]}
          category={component}/>
      })
  }
}

For a function component, use the useEffect hook. This will be called after every render (unless you specify otherwise).

const Example = (props) => {
  useEffect(() => {
    console.log('done rendering');
  });

  return keys.map((component) => {
    return sorted[component].length > 0 &&
      <Card key={component} articles={sorted[component]}
        category={component}/>
    })
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...