[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 ...
随机推荐
- POJ2976 Dropping tests(01分数规划)
题意 给你n次测试的得分情况b[i]代表第i次测试的总分,a[i]代表实际得分. 你可以取消k次测试,得剩下的测试中的分数为 问分数的最大值为多少. 题解 裸的01规划. 然后ans没有清0坑我半天. ...
- HDU 4960 Another OCD Patient 简单DP
思路: 因为是对称的,所以如果两段是对称的,那么一段的前缀和一定等于另一段的后缀和.根据这个性质,我们可以预处理出这个数列的对称点对.然后最后一个对称段是从哪里开始的,做n^2的DP就可以了. 代码: ...
- 百度IOT
万物互联 http://www.jianshu.com/p/3d9846bf42bd 百度天工
- 洛谷—— P2419 [USACO08JAN]牛大赛Cow Contest
https://www.luogu.org/problem/show?pid=2419 题目背景 [Usaco2008 Jan] 题目描述 N (1 ≤ N ≤ 100) cows, convenie ...
- android内存释放处理
不知道大家对android内存释放都做什么样的处理,本人接触android不久,近期开发小游戏的过程中,由于游戏界面组件较多.刚玩游戏的时候感觉还好,可是重复进入游戏界面玩几次之后,游戏就会卡顿,我瞬 ...
- 免费WiFi初体验——个小白的WiFi旅程
说来羞愧,真正接触到WiFi还是在毕业后,此前自己封闭在一个人的世界,再加上外在学校的包围,我还成了个"山里"的孩子. 去年毕业了,也算是个90后,可自觉得心态过于成熟.了解外界太 ...
- thinkphp中cookie和session中操作数组的方法
thinkphp中cookie和session中操作数组的方法 一.ThinkPHP模板中如何操作session,以及如果session中保存的是数组的情况 在ThinkPHP的模板中操作sessio ...
- php 扩展
如何利用PHP扩展函数,扩展出自己的函数等 php扩展函数有哪些zend_parse_parameters() spprintf() RETURN_STRINGL()
- C++中冒号(:)的作用
摘于:http://blog.csdn.net/zimingjushi/article/details/6549390 (1)表示机构内位域的定义(即该变量占几个bit空间) typedef stru ...
- React开发实时聊天招聘工具 -第五章 需求分析
Axios的使用 axios.get('/data') .then(res=>{ if(res.status==200) this.setState(data:res.data) })