React. Basic example of re-rendering using react-router. +100 rep

删除回忆录丶 提交于 2019-12-24 19:45:13

问题


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



来源:https://stackoverflow.com/questions/51180902/react-basic-example-of-re-rendering-using-react-router-100-rep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!