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. 【转载】Perl中字符串编码的处理

    在 Perl看来, 字符串只有两种形式. 一种是octets, 即8位序列, 也就是我们通常说的字节数组. 另一种utf8编码的字符串, perl管它叫string. 也就是说: Perl只熟悉两种编 ...

  2. ATP自造8Gb内存颗粒供DDR3使用

    随着整个行业已经全面转向DDR4内存,不少厂商都陆续停产了DDR3,并准备好了迎接DDR5,但对于很多特殊用户,尤其是网络和嵌入式领域,仍然对DDR3有着强劲且持续的需求. 工业内存存储厂商ATP E ...

  3. Unity C# 设计模式(六)原型模式

    定义:用原型实例指定创建对象的种类,并通过拷贝这些原型来创建新的对象. 优点: 1.原型模式向客户隐藏了创建新实例的复杂性 2.原型模式允许动态增加或较少产品类. 3.原型模式简化了实例的创建结构,工 ...

  4. Unity Shader (四)片段程序示例

      1.环境光+漫反射+高光+点光源 Shader "Custom/Example_Frag_1" { properties { _MainColor(,,,) _Specular ...

  5. Android中App可分配内存的大小

    现在真实测试结果: 1,为了搞清楚每个应用程序在Android系统中最多可分配多少内存空间,我们使用了真机进行测试,测试机型为魅族MX4 Pro,3G内存. 测试方法是直接申请一块较大的内存空间,看应 ...

  6. JAVA并发--volatile

    学过计算机组成原理的一定知道,为了解决内存速度跟不上CPU速度这个问题,在CPU的设计中加入了缓存机制,缓存的速度介于CPU和主存之间.在进行运算的时候,CPU将需要的数据映射一份在缓存中,然后直接操 ...

  7. thinkphp中cookie和session中操作数组的方法

    thinkphp中cookie和session中操作数组的方法 一.ThinkPHP模板中如何操作session,以及如果session中保存的是数组的情况 在ThinkPHP的模板中操作sessio ...

  8. 简单的quartz 可视化监听管理界面

    spring-quartz. 导包.配置,不在此介绍. 简单的quartz管理界面,包括触发器的暂停.恢复.删除.修改(暂无),任务的运行.触发添加.创建,删除. 扩展内容:日志的管理,添加和创建触发 ...

  9. 初学PHP&MySQL 2014-05-31 12:40 92人阅读 评论(0) 收藏

    PHP echo  print 都能输出文本 date(format,timestamp)可以格式化时间戳 mktime()可以返回指定日期的时间戳 include 'filename'或者 requ ...

  10. Chromium Graphics: HW Video Acceleration in Chrom{e,ium}{,OS}

    HW Video Acceleration in Chrom{e,ium}{,OS} Ami Fischman <fischman@chromium.org> Status as of 2 ...