React router - Update URL hash without re-rendering page

后端 未结 3 1483
青春惊慌失措
青春惊慌失措 2020-12-14 07:47

Using react-router I\'m looking for a way to update the page URL / hash, without the router re-rendering the whole page.

I am developing a full page carousel, and wo

相关标签:
3条回答
  • 2020-12-14 08:04

    For React router v4 you need to use history and pass it as prop to the Router. Router will then pass history object to your component as a prop and you can use it like so:

    // In your component
    
    this.props.history.push("#testing")
    

    History file

    // history.js 
    import createHistory from "history/createBrowserHistory";
    
    export default createHistory();
    

    Then, wherever you are declaring your router, pass the history prop

    import history from "./history";
    import { Router } from "react-router-dom";
    
        <Router history={history}>
          // ... Your component
        </Router>
    
    0 讨论(0)
  • 2020-12-14 08:24

    1.0

    react-router no longer sets a key on your routes. If you do need to set a key from a route handler, put it on a surrounding element.

    return (
      <div key={this.props.params.bookId}>
        {this.props.children}
      </div>
    );
    

    0.13

    It's now <ReactRouter.RouteHandler key="anything" />, but this is also no longer really needed due to changes in react-router. See the changelog for more details.

    0.12

    Currently, react-router sets a key on your handler based on the current route. When react does its diff, and notices a different key, it throws out the entire subtree both in virtual and real dom, and rerenders.

    To prevent this, you can override react-router's key when using activeRouteHandler()

    this.props.activeRouteHandler({key: "anything"})
    
    0 讨论(0)
  • 2020-12-14 08:29

    It is a pain to work with react-router because it involves breaking changes in every major and minor release

    React Router v2.0 rc5

    import { hashHistory } from 'react-router'
    this.props.location.query.t = key;
    hashHistory.replace(this.props.location);
    
    0 讨论(0)
提交回复
热议问题