简体   繁体   中英

ReactJS Browser Back button to refresh the same component

I have a Search page that is composed of multiple react components. A user will type a keyword to search and see the results, all happens on the same page.

User can come to this page by clicking a search button on home page or to this page directly by typing the URL. URL pattern is http://example.com/search?q=text

Here is my page markup

在此处输入图片说明

<Search> component will update the redux state and issue required backend calls to get the data on componentDidMount lide cycle event.

Component flow:

  1. <Search /> will read the query string and updates redux state which triggers two API calls, one for facets and another for results.
  2. <SearchBox /> component will show this text in the textbox
  3. <Facets /> and <Results /> display data based on redux state updated by the backend calls.
  4. <CountBar /> displays some aggregated information of the results

After the initial load, User can type a search term in the textbox in <SearchBox /> and press enter . This button click will update the redux state and issues a history.push("/search?q=test") . This repeats the process mentioned above and updates the URL. Everything is fine till here.

After couple of searches, if users presses browser back button <Search /> component is not updating the data based on the query string as componentDidMount is not triggered. None of the child component events are triggered. I tried using componentWillRecieveProps but this is going into an infinite loop.

One option I can think of is to pass the query string as props to child components (Don't if that helps to avoid this problem) but I need this query string in redux state, as I have few other routes that needs the last searched query string value.

So now I have few questions:

  1. What is the best way to handle browser back button in this scenario?
  2. Here component is responsible for updating the query string to redux, Is that a good behavior?
  3. I am using React 16.7 and not using React Hooks. Is upgrading to latest version or using Hooks will help in any way?

Thank you for your help.

I might have missed something when I tried componentWillReceivePorps initially. I tried with this and it is working as expected. In this method I am comparing newprops with existing props to see if they are different and make API call accordingly. For the first page load componentDidMount will make the API call.

componentWillReceiveProps(newProps: any){

    let keyword = querystring.parse(this.props.location.search).q;
    let newKeyword = querystring.parse(newProps.location.search).q;

    if(keyword != newKeyword){
      //trigger redux action
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM