React. Basic example of re-rendering using react-r

2019-08-26 22:52发布

问题:

I'm newbie. And I'm newbie at React. I'm trying react-router. I saw this example: https://reacttraining.com/react-router/web/example/basic.

I reproduced it on Codesandbox.io here: https://codesandbox.io/s/7jxq0j6qp0

I don't understand why the Menu is re-rendering itself when I change URL using menu's links.

If you open console you can see it.

Why?

I think it should not re-render itself. Just the route section. Where am I wrong?

回答1:

You can write your component as PureComponent. Since there is no prop changes right now it won't be re-rendered:

class Menu extends React.PureComponent {
  render() {
    console.log("Menu render() - ", Date.now());
    return (
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/topics">Topics</Link>
          </li>
        </ul>

        <hr />
      </div>
    );
 }
}

But, please be aware of the negative sides of this method for other use cases: Dealing with Update Blocking