Guest User

Untitled

a guest
Mar 20th, 2018
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
  2. ReactDOM.render(
  3. <Router>
  4. <App />
  5. </Router>,
  6. document.getElementById('root'),
  7. );
  8.  
  9. import React, { Component } from 'react';
  10. import { Switch, Route } from 'react-router-dom';
  11. import { withRouter } from 'react-router'
  12.  
  13. class App extends Component {
  14. state = { prevLocation: '' };
  15.  
  16. // Use the context api to retrieve the value in your Link
  17. getChildContext = () => (
  18. {
  19. prevLocation: this.state.prevLocation,
  20. }
  21. );
  22.  
  23. componentWillReceiveProps(nextProps) {
  24. if (nextProps.location !== this.props.location) {
  25. this.setState({ prevLocation: this.props.location.pathname });
  26. }
  27. }
  28.  
  29. render() {
  30. return (
  31. <div>
  32. <Switch>
  33. // ...
  34. </Switch>
  35. </div>
  36. );
  37. }
  38. }
  39.  
  40. App.childContextTypes = {
  41. prevLocation: PropTypes.string,
  42. };
  43.  
  44. export default withRouter(App);
  45.  
  46. import React from 'react';
  47. class GoBack extends React.Component {
  48. render() {
  49. return <Link to={this.context.prevLocation}>click</Link);
  50. }
  51. }
  52.  
  53. GoBack.contextTypes = {
  54. prevLocation: PropTypes.string,
  55. };
Add Comment
Please, Sign In to add comment