In Single Page Apps we're used to fetch the data on event callbacks. That disables the capacity to use the URL to share it to someone else and get to the same state of the app, just like in non Single Page Apps.

This lesson shows you how to use React and React Router to use the URL as the source of truth for your app state.

Doing this in React, we can devide into three steps:

1. We can use 'withRouter' HOC to get 'location' props.

2. Handle refresh case: when page refresh, we want to check whether there is query string, if yes, then we need to fetch the data from the BE.

3, Hnadle query string changes case: when the query string changes, we want to use 'componentWIllReceiveProps' lifecycle to get udpated query string, then fetch the data from BE.

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"; const styles = {
fontFamily: "sans-serif",
textAlign: "center"
}; // Step 1
const App = withRouter(() => (
<div style={styles}>
<Switch>
<Route exact path="/" component={Search} />
</Switch>
</div>
)); render(
<HashRouter>
<App />
</HashRouter>,
document.getElementById("root")
); ----------------------- import React, { Component } from "react"; const baseUrl = "https://jsonplaceholder.typicode.com/posts"; class Hello extends Component {
state = {
results: []
}; // Step 2
componentDidMount() {
const queryString = this.props.location.search; if (queryString) {
this.fetch(queryString);
}
} // Step 3
componentWillReceiveProps({ location }) {
const oldQueryString = this.props.location.search;
const queryString = 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;
const queryString = value ? `?q=${value}` : "";
const currentUrl = window.location.href.split("?")[];
window.location = `${currentUrl}${queryString}`;
}; render() {
return (
<div>
<input ref={input => (this.input = input)} onBlur={this.handleChange} />
<br />
{this.state.results.map((res, i) => <p key={i}>{res.title}</p>)}
</div>
);
}
} export default Hello;

最新文章

  1. Qt - 错误总结 - 在自定义类头文件中添加Q_OBJECT 编译时报错(undefined reference to ‘vtable for xxThread)
  2. Android 异步任务,通过PHP访问数据库,多线程,线程间通讯
  3. gulp 插件
  4. 使用dom元素和jquery元素实现简单增删改的练习
  5. 应用alter index &#215;&#215;&#215; monitoring usage;语句监控索引使用与否
  6. Jenkins学习八:Jenkins语言本地化
  7. HTML5自学笔记[ 18 ]canvas绘图基础5
  8. install python module
  9. 记一次SSH登陆失败问题的定位
  10. [上传下载] C#FileUp文件上传类 (转载)
  11. 关于手机端CSS Sprite图标定位的一些领悟
  12. JavaScript创建类的方式
  13. Java 反射机制浅析
  14. Jquery 遍历数组之$().each方法与$.each()方法介绍
  15. 在Windows上使用CodeLite+MinGW+Clang进行开发
  16. 最新版solr7.2集群搭建详细步骤
  17. cesium 之地图显示坐标、比例尺、海拔高度效果篇(附源码下载)
  18. [Swift]LeetCode623. 在二叉树中增加一行 | Add One Row to Tree
  19. Unity Ragdoll 实现死亡效果 心得+坑点总结
  20. selenium python 一些操作和定位收集

热门文章

  1. 单调队列&amp;单调栈归纳
  2. Mac系统下安装pip
  3. Android中图片优化之webp使用
  4. [Recompose] Refactor React Render Props to Streaming Props with RxJS and Recompose
  5. swift学习之数组
  6. File的getPath()和getAbsolutePath()和getCanonicalPath()的差别
  7. 怎样安装Windows7操作系统
  8. 30.angularJS第一个实例
  9. 123.static静态函数与类模板
  10. 如何使用通用pe工具箱破解开机密码