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;

[React] Use the URL as the source of truth in React的更多相关文章

  1. 十四、 React路由(react-router4.x): 动态路由、get传值、React中使用url模块

    概述 新闻列表 -跳转-> 详情页 时,想把列表对应的id传到详情页里,可用到三种传值方法: 1.动态路由传值 2.get传值 3.localstorage传值 一.动态路由传值 [App.js ...

  2. 《React Native 精解与实战》书籍连载「React Native 源码学习方法及其他资源」

    此系列文章将整合我的 React 视频教程与 React Native 书籍中的精华部分,给大家介绍 React Native 源码学习方法及其他资源. 最后的章节给大家介绍 React Native ...

  3. 《React Native 精解与实战》书籍连载「React Native 底层原理」

    此文是我的出版书籍<React Native 精解与实战>连载分享,此书由机械工业出版社出版,书中详解了 React Native 框架底层原理.React Native 组件布局.组件与 ...

  4. 《React Native 精解与实战》书籍连载「React 与 React Native 简介」

    此文是我的出版书籍<React Native 精解与实战>连载分享,此书由机械工业出版社出版,书中详解了 React Native 框架底层原理.React Native 组件布局.组件与 ...

  5. Discuz使用tools修复数据文件后,访问URL多出/source/plugin/tools,导致文章栏目无法访问

    今天我的婚嫁亲子网数据库出了点错误,于是就用dz官方的tool工具修复了以下,然后就发生了这个错误.. 本来频道页面的地址是:http://www.ifen8.com/article/ 结果自动跳转成 ...

  6. react跳转url,跳转外链,新页面打开页面

    react中实现在js中内部跳转路由,有两种方法. 方法一: import PropTypes from 'prop-types'; export default class Header exten ...

  7. 《React Native 精解与实战》书籍连载「React Native 网络请求与列表绑定」

    此文是我的出版书籍<React Native 精解与实战>连载分享,此书由机械工业出版社出版,书中详解了 React Native 框架底层原理.React Native 组件布局.组件与 ...

  8. react网页版聊天|仿微信、微博web版|react+pc端仿微信实例

    一.项目介绍 基于react+react-dom+react-router-dom+redux+react-redux+webpack2.0+nodejs等技术混合开发的仿微信web端聊天室react ...

  9. React virtual DOM explained in simple English/简单语言解释React的虚拟DOM

    初学React,其中一个很重要的概念是虚拟DOM,看了一篇文章,顺带翻译一下. If you are using React or learning React, you must have hear ...

随机推荐

  1. 常用模块(hashlib、suprocess、configparser)

    hashlib模块 hash是一种接受不了内容的算法,(3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法),该算 ...

  2. 【问题:SSH】win10使用SSH链接服务器时,提示:Host key verification failed

    异常原因:当前连接新建的验证信息与之前保存的验证信息不一致,将原来的验证信息删除就可以了. 1 使用以下命令,清空之前缓存的信息.或者直接打开C:\Users\Nolan\.ssh\known_hos ...

  3. 今日SGU 5.26

    #include<bits/stdc++.h> #define de(x) cout<<#x<<"="<<x<<endl ...

  4. iOS-入门HelloWorld

    刚刚搞了几个图形界面的iOS应用程序,难的没搞定一个,HelloWorld程序倒是很简单. 新建Project,iOS->Application->Single View Applicat ...

  5. 二 HTable 源码导读

    户端调优的方法里面无非就这么几种:1)关闭autoFlush2)关闭WAL日志3)把writeBufferSize设大一点,一般说是设置成5MB        经过实践,就第二条关闭日志的效果比较明显 ...

  6. WIN10远程桌面连接--“出现身份验证错误。要求的函数不支持”

    最近WIN10升级补丁后发现远程桌面无法连接了,报“出现身份验证错误.要求的函数不支持”的错误: 解决办法: 第一种,配置本地自己的电脑,开始菜单->搜索gpedit.msc并打开   打开配置 ...

  7. 剑指Offer面试题27(Java版):二叉搜索树与双向链表

    题目:输入一颗二叉搜索树,将该二叉搜索树转换成一个排序的双向链表.要求不能创建新的结点.仅仅能调整树中结点指针的指向. 比方例如以下图中的二叉搜索树.则输出转换之后的排序双向链表为: 在二叉树中,每一 ...

  8. uva 1292 树形dp

    UVA 1292 - Strategic game 守卫城市,城市由n个点和n-1条边组成的树,要求在点上安排士兵,守卫与点相连的边.问最少要安排多少士兵. 典型的树形dp.每一个点有两个状态: dp ...

  9. An internal error occurred during: &quot;Checking tomcat state&quot;. Error while reading server.xml

    An internal error occurred during: "Checking tomcat state". Error while reading server.xml ...

  10. generate the call load file

    #!/usr/bin/perl -w $e911_call_percent = 0.0; $ims_node_number = 12; $local_ip = "10.86.52.2&quo ...