React router v4 onUpdate

I recently updated the response of version 4 of the router. In the previous version, I used a callback onUpdateto call the function so that the page scrolls at the top when the route has been changed.

It looks like it's onUpdateout of date, and I can't find anywhere in the docs that it has been replaced.

Anyone else run into this problem?

const handlePageChange = () => {
    window.scrollTo(0, 0);
};  

ReactDOM.render(
    <Provider store={store}>
        <Router onUpdate={handlePageChange} history={browserHistory}>
            <Redirect from="/" to="/music" />
            {routes}
        </Router>
    </Provider>,
    document.getElementById('root')
);
+4
source share
4 answers

"onUpdate" is depreciating. You can use the "onEnter" property in "Routes".

<Router history={browserHistory}>
  <Route path="/" component={App} >
    <IndexRoute component={Home} />
    <Route path="/contact-us" component={ContactUs} onEnter={handlePageChange}/>
  </Route>
</Router>

It is also necessary to change the function "handlePageChange", as shown below:

const handlePageChange = () => {
    window.scrollTo(0, 0);
    if ('scrollRestoration' in history) {
        history.scrollRestoration = 'manual';
    }
}
+2
source

- context.router.subscribe ...

- :

import React from 'react';

class App extends React.Component {
  //something like this in your code
  componentDidMount() {
    this.context.router.subscribe(() => {
        console.log("change router");
    })
   }
    render() {
    return <button>hi</button>;
  }
}

export default App;
0

@ , .

React Context API, , contextTypes:

static contextTypes = {
  router: PropTypes.object
};

, .

, ( ?) subscribe . :

this.context.router.history.listen(handlePageChange)

, componentDidMount.

0

:

class NotFoundView extends React.Component {
  componentDidMount() {
    window.scrollTo(0, 0);
  }

  render() {
    var props = this.props;

    return (
      <div className="NotFound">
        <HeaderContainer />

        <h1>Coming Soon!</h1>
      </div>
    )
  }
}

export default NotFoundView;
0

Source: https://habr.com/ru/post/1677675/


All Articles