Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to rerender a component when hash change and change the state

I want to monitor hash change and then change the state and rerender the component. so I want to know where to monitor the hash change in component lifecycle

example:

#/detail/:id  =>  #/detail

{info:[a:1,b:2]} => {info:[]}

.#/detail/:id and #/detail are the same components

like image 775
李明洋 Avatar asked Aug 16 '16 02:08

李明洋


2 Answers

If you want your component to have event listeners, you want to add those event listeners in componentDidMount, and remove the event listeners in componentWillUmount.

componentDidMount() {
    window.addEventListener("hashchange", this.doSomething, false);
}

componentWillUnmount() {
    window.removeEventListener("hashchange", this.doSomething, false);
}
like image 124
captray Avatar answered Oct 13 '22 14:10

captray


Use HashRouter in index.js and withRouter to get path parameters and getDerivedStateFromProps to handle the states based on the url's hash.

index.js

import ReactDOM from 'react-dom';
import { HashRouter } from "react-router-dom";

import App from './App';

ReactDOM.render(
  <HashRouter>
    <App />
  </HashRouter>,
  document.getElementById('root')
);

App.js

import { withRouter } from 'react-router-dom';

class App extends Component {

  state = { productId: null };

  static getDerivedStateFromProps(nextProps){
    const { location: { pathname } } = nextProps;       // pathname e.g.: '/detail/:8'
    const productId = pathname.split(':')[1] || null;   // ProductId: 8 OR null;
    return { productId };
  }

  ...

}

export default withRouter(App);
like image 30
gazdagergo Avatar answered Oct 13 '22 14:10

gazdagergo