Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - Will component Re-Render when the path is changed?

My App component definition looks as follows:

function App() {
    return (
        <Router>
            <Navbar/>
            <Switch>
                <Route path="/howitworks">
                    <HowItWorks/>
                </Route>
                <Route path="/aboutus">
                    <AboutUs/>
                </Route>

                <Route path="/">
                    <Home/>
                </Route>
            </Switch>
            <Footer/>
        </Router>
    )
}

I have a question regarding to route and re-render.

For example, when I route from / to /howitworks, then the component <HowItWorks/> is going to be rendered. Routing back to / from /howitworks, will <Home/> component be re-rendered?

The <Home/> component contains only text. It does not contain any logic.

Update

I have created an example on https://codesandbox.io/s/react-router-forked-2mp45.

When you consider the about component, how it is defined:

import React, { useState } from "react";

const About = () => {
  const [state, _] = useState(2);

  React.useEffect(
    (_) => {
      console.log("state changed");
    },
    [state]
  );

  return (
    <div>
      <h2>About</h2>
    </div>
  );
};

export default About;

and every time when /aboutus is clicked, it shows always the message:

state changed

that means for me, every time when the path changed, then re-render will always happen.

Am I right?

question from:https://stackoverflow.com/questions/65602448/will-component-re-render-when-the-path-is-changed

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

1 Reply

0 votes
by (71.8m points)

Yes, re-render happens on path change. Re-render essentially means painting the screen again.

If you think about component being mounting again the component unmounts too on path change.

Here is an example reflecting that https://codesandbox.io/s/react-router-forked-nlqzg?file=/components/About.js


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...