[React] Use the URL as the source of truth in React
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的更多相关文章
- 十四、 React路由(react-router4.x): 动态路由、get传值、React中使用url模块
概述 新闻列表 -跳转-> 详情页 时,想把列表对应的id传到详情页里,可用到三种传值方法: 1.动态路由传值 2.get传值 3.localstorage传值 一.动态路由传值 [App.js ...
- 《React Native 精解与实战》书籍连载「React Native 源码学习方法及其他资源」
此系列文章将整合我的 React 视频教程与 React Native 书籍中的精华部分,给大家介绍 React Native 源码学习方法及其他资源. 最后的章节给大家介绍 React Native ...
- 《React Native 精解与实战》书籍连载「React Native 底层原理」
此文是我的出版书籍<React Native 精解与实战>连载分享,此书由机械工业出版社出版,书中详解了 React Native 框架底层原理.React Native 组件布局.组件与 ...
- 《React Native 精解与实战》书籍连载「React 与 React Native 简介」
此文是我的出版书籍<React Native 精解与实战>连载分享,此书由机械工业出版社出版,书中详解了 React Native 框架底层原理.React Native 组件布局.组件与 ...
- Discuz使用tools修复数据文件后,访问URL多出/source/plugin/tools,导致文章栏目无法访问
今天我的婚嫁亲子网数据库出了点错误,于是就用dz官方的tool工具修复了以下,然后就发生了这个错误.. 本来频道页面的地址是:http://www.ifen8.com/article/ 结果自动跳转成 ...
- react跳转url,跳转外链,新页面打开页面
react中实现在js中内部跳转路由,有两种方法. 方法一: import PropTypes from 'prop-types'; export default class Header exten ...
- 《React Native 精解与实战》书籍连载「React Native 网络请求与列表绑定」
此文是我的出版书籍<React Native 精解与实战>连载分享,此书由机械工业出版社出版,书中详解了 React Native 框架底层原理.React Native 组件布局.组件与 ...
- react网页版聊天|仿微信、微博web版|react+pc端仿微信实例
一.项目介绍 基于react+react-dom+react-router-dom+redux+react-redux+webpack2.0+nodejs等技术混合开发的仿微信web端聊天室react ...
- React virtual DOM explained in simple English/简单语言解释React的虚拟DOM
初学React,其中一个很重要的概念是虚拟DOM,看了一篇文章,顺带翻译一下. If you are using React or learning React, you must have hear ...
随机推荐
- Java基础学习总结(21)——数组
一.数组的基本概念 数组可以看成是多个相同类型数据组合,对这些数据的统一管理. 数组变量属引用类型,数组也可以看成是对象,数组中的每个元素相当于该对象的成员变量. 数组的元素可以是任何数据类型,包括基 ...
- ArcGIS api for javascript——显示多个查询结果
描述 本例展示了在重叠的多边形处理查询的一种方式.单击一个石油和天然气的字段来查看地图上的高亮显示.如果仅仅点击一个要素,能够在单击一次来查看包含一些属性的InfoWindow.如果偶然单击到重叠的要 ...
- Liquibase被锁
经常运行过程中出现 Liquibase - Waiting for changelog lock Waiting for changelog lock.... Running the migratio ...
- Nios II 系统时钟timestamp的应用
在用Nios II做外设时序驱动的时候,经常会用延时函数.有时会常使用某个FPGA芯片和时钟,比如笔者一直使用的芯片是cyclone系列 EP2C35F484C8N,PLL输入SOPC时钟是50M.因 ...
- EF数据迁移命令
在包管理器控制台中输入命令“enable-migrations”,然后按Enter键!Visual Studio将生成一个名为“Configurations.cs”的文件; 你可以安全地忽略它,但你需 ...
- Redis之创建
redis配置文件信息 public sealed class RedisConfigInfo { /// <summary> /// 可写的Redis链接地址 /// format:ip ...
- Android Unknown failure (Failure - not installed for 0)
File->Settings->Build,Execuion,Deployment->Instant Run然后把Enable Instant Run to...那一项的勾去掉就好了
- Servlet之doPost获取表单参数
/** * 获取表单参数 */ private void readForm() { // TODO Auto-generated method stub Enumeration e = request ...
- C# 利用反射和特性 来做一些事情
特性代码: [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public clas ...
- startActivityForResult and onActivityResult
startActivityForResult and onActivityResult startActivityForResult 开启Activity 组织数据之后 发送,onActivityRe ...