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

查看:137
本文介绍了javascript - 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者具体机制有何区别?

解决方案

应该是hashHistory本身的bug,https://github.com/ReactTrain...

这篇关于javascript - react-router的hashHistory导致组件渲染2次问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆