In a single Page, Apps we ' re used to fetch the data on event callbacks. That disables the capacity-the URL to share it to someone else and get-to-the-same state of the app, just like in n On the single Page Apps.
This lesson shows-to-use React and React Router-use the URL as the source of the truth for your app state.
Doing this on React, we can devide into three steps:
1. We can use the ' withrouter ' HOC to get the ' location ' props.
2. Handle Refresh Case:when page refresh, we want to check whether there are query string, if yes, then we need to fetch t He data from the being.
3, hnadle query string changes case:when the query string changes, we want to use ' componentwillreceiveprops ' lifecycle t o Get udpated query string, then fetch the data from IS.
Import React from "react"; import {render} from "React-dom"; import {withrouter} from "React-router"; import {hashrouter, Route, Switch} from 'React-router-dom'; import Search from "./search";ConstStyles ={fontFamily:"Sans-serif", TextAlign:"Center"};//Step 1ConstAPP = Withrouter (() = ( <div style={styles}> <Switch> <route exact path="/"Component={search}/> </Switch> </div>) ); Render (<HashRouter> <app/> </HashRouter>, document.getElementById ("Root"));-----------------------import React, {Component} from "react";ConstBASEURL ="https://jsonplaceholder.typicode.com/posts";classHello extends Component { state={results: []}; //Step 2Componentdidmount () {ConstQueryString = This. Props.location.search; if(queryString) { This. Fetch (queryString); } } //Step 3componentwillreceiveprops ({location}) {ConstOldquerystring = This. Props.location.search; ConstQueryString =Location.search; if(Oldquerystring!==queryString) { This. Fetch (queryString); }} Fetch= (queryString ="") ={fetch (' ${baseurl}${querystring} '). Then (res=Res.json ()). Then (Results= This. SetState ({results})); }; HandleChange= EV + = { Const{Value} = This. Input; ConstqueryString = value? '? Q=${value} ':""; ConstCurrenturl = Window.location.href.split ("?")[0]; Window.location=' ${currenturl}${querystring} '; }; Render () {return ( <div> <inputref={input = ( This. Input = input)} onblur={ This. handlechange}/> <br/> { This. State.results.map (res, i) = <p key={i}>{res.title}</p>)} </div> ); }}exportdefaultHello;
[React] Use the URL as the source of truth in React