react-router的hashHistory导致组件渲染2次问题

index.js代码如下

import React from 'react'
import { render } from 'react-dom'
import { Router, Route, Link, IndexLink, hashHistory, IndexRoute } from 'react-router'
import PropTypes from 'prop-types'

const App = ({ children }) => (
  <div>
    <h1>App</h1>
    <ul>
      <li><IndexLink to="/">Dashboard</IndexLink></li>
      <li><Link to="/about">About</Link></li>
    </ul>
    {children}
  </div>
)

App.proptypes = {
  children : PropTypes.node
}

const About = () => {
  console.log('about')
  return (
    <h3>About</h3>
  )
}

const Dashboard = () => (
  <div>Welcome to the app!</div>
)

const routerElement = (
  <Router history={hashHistory}>
    <Route path="/" component={App}>
      <IndexRoute component={Dashboard}/>
      <Route path="about" component={About}/>
    </Route>
  </Router>
)
render(routerElement, document.getElementById('app'))

在渲染<About /> 的时候会打印‘about’。
操作流程:

  1. 进入/,首页。

  2. 点击about链接路由跳转到About。

  3. 控制台查看日志,发现打印了2次‘about’。
    想问的是一次跳转为何会渲染2次<About />?

另外,把hashHistory换成browserHistory,就正常打印一次了。这2者具体机制有何区别?

阅读 2.6k
1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题