[Redux] Fetching Data on Route Change
We will learn how to fire up an async request when the route changes.
A mock server data:
/** /api/index.js
* Created by wanzhen on 7.6.2016.
*/
import { v4 } from 'node-uuid'; // This is a fake in-memory implementation of something
// that would be implemented by calling a REST server. const fakeDatabase = {
todos: [{
id: v4(),
text: 'hey',
completed: true,
}, {
id: v4(),
text: 'ho',
completed: true,
}, {
id: v4(),
text: 'let’s go',
completed: false,
}],
}; const delay = (ms) =>
new Promise(resolve => setTimeout(resolve, ms)); export const fetchTodos = (filter) =>
delay(500).then(() => {
switch (filter) {
case 'all':
return fakeDatabase.todos;
case 'active':
return fakeDatabase.todos.filter(t => !t.completed);
case 'completed':
return fakeDatabase.todos.filter(t => t.completed);
default:
throw new Error(`Unknown filter: ${filter}`);
}
});
We want to replace localStorge with mock server data, so remove the localStorge code:
// configureStore.js
import { createStore } from 'redux';
import todoApp from './reducers';
const addLoggingToDispatch = (store) => {
const rawDispatch = store.dispatch;
// If browser not support console.group
if (!console.group) {
return rawDispatch;
}
return (action) => {
console.group(action.type);
console.log('%c prev state', 'color: gray', store.getState());
console.log('%c action', 'color: blue', action);
const returnValue = rawDispatch(action);
console.log('%c next state', 'color: green', store.getState());
console.groupEnd(action.type);
return returnValue;
};
};
const configureStore = () => {
const store = createStore(todoApp);
// If in production do not log it
if (process.env.NODE_ENV !== 'production') {
store.dispatch = addLoggingToDispatch(store);
}
return store;
};
export default configureStore;
We want to fetch data inside the component: VisibleTodoList.js.
The good place to fetch data is in 'componentDidMount' lifecycle: This will fetch the initial data, which only run once.
Thats not enough, we still need when the filter changes, it also need to fetch data, for that we can use another lifecycle 'componentDidUpdate'.
import {connect} from 'react-redux';
import {toggleTodo} from '../actions';
import TodoList from './TodoList';
import {withRouter} from 'react-router';
import {getVisibleTodos} from '../reducers';
import React, {Component} from 'react';
import {fetchTodos} from '../api';
class VisibleTodoList extends Component {
// Fetch data when component mount
componentDidMount() {
fetchTodos(this.props.filter)
.then((todos) => {
console.log(this.props.filter, todos);
})
}
// Check the filter props, when it changes, fetch data again
componentDidUpdate(prevProps) {
if (this.props.filter !== prevProps.filter) {
fetchTodos(this.props.filter)
.then((todos) => {
console.log(this.props.filter, todos);
})
}
}
render() {
return (
<TodoList {...this.props}/>
)
}
}
const mapStateToProps = (state, {params}) => {
const filter = params.filter || 'all';
//todos, filter Will available in props
return {
todos: getVisibleTodos(state, filter),
filter,
};
};
//re-assign the VisibleTodoList
VisibleTodoList = withRouter(connect(
mapStateToProps,
{onTodoClick: toggleTodo}
)(VisibleTodoList));
export default VisibleTodoList;
[Redux] Fetching Data on Route Change的更多相关文章
- Part 39 AngularJS route change events
In this video we will discuss1. Different events that are triggered when a route change occurs in an ...
- Part 38 AngularJS cancel route change
n this video we will discuss, how to cancel route change in Angular with an example. This is extreme ...
- Fetching data with Ajax小例子
ajax获取数据示例: 示例1 通过ajax获取txt文件里面的内容示例: <html> <head> <title>Ajax at work</title& ...
- [Angular 2] implements OnInit, OnDestory for fetching data from server
Link: https://angular.io/docs/js/latest/api/core/OnInit-interface.html, https://www.youtube.com/watc ...
- 『奇葩问题集锦』Ruby 切换淘宝源报错WARNING: Error fetching data: SSL_connect returned=1 errno=0 state=SSLv3 read s erver certificate B: certificate verify failed
===>首先需要使用https<===https://ruby.taobao.org/ 第一步 下载http://pan.baidu.com/s/1kU0rxtH 复制到ruby安装的根目 ...
- Kafka消费者拉取数据异常Unexpected error code 2 while fetching data
Kafka消费程序间歇性报同一个错: 上网没查到相关资料,只好自己分析.通过进一步分析日志发现,只有在拉取某一个特定的topic的数据时报错,如果拉取其他topic的数据则不会报错.而从这个异常信息来 ...
- 使用 empApi 组件实现 Change Data Capture 功能
Change Data Capture 功能是从 Winter '19 版本开始正式启用的功能. 它是基于"发布-订阅"模式设计,可以将 Salesforce 中记录的改变自动推送 ...
- [Angular2 Router] Resolving route data in Angular 2
From Article: RESOLVING ROUTE DATA IN ANGULAR 2 Github If you know Anuglar UI router, you must know ...
- [Redux] Important things in Redux
Root Smart component can be overloaded, divide 'smart' component wisely & using Provider. Proble ...
随机推荐
- WebComponent
WebComponent 前言 最近加入到新项目组负责前端技术预研和选型,一直偏向于以Polymer为代表的WebComponent技术线,于是查阅各类资料想说服老大向这方面靠,最后得到的结果是:& ...
- 如何通过SNMP的OID识别不同厂商的设备
众所周知,SNMP作为通用的网络协议常用于系统监控之中,那么如何借助SNMP来识别不同厂商的设备呢? 事实上,在SNMP的OID树状图中专门有一个节点用于识别各不同的厂商,这个节点是: iso(1) ...
- 第 8 章 适配器模式【Adapter Pattern】
以下内容出自:<<24种设计模式介绍与6大设计原则>> 好,请安静,后排聊天的同学别吵醒前排睡觉的同学了,大家要相互理解嘛.今天讲适配器模式,这个模式也很简单,你笔记本上的那个 ...
- webservice 的权限验证
1. http://blog.csdn.net/jaune161/article/details/25602655 2. http://wcp88888888.iteye.com/blog/13993 ...
- SQL 各种连接:内连接,外连接(左外,右外,完全外)
在讲述之前,假设有如下两个表EMP, DEPT, 并且他们数据如下:
- QLGame 2d Engine Android端环境搭建(通过jni读取assets目录的文件)
QLGame 2d Engine win端已经实现了一个动物的动画了,初步的东西已经完成,考虑在Android端也实现这些基本的东西,这样跨平台的引擎也就实现了! 要在Android下编程,首先要实现 ...
- 【HDU 3810】 Magina (01背包,优先队列优化,并查集)
Magina Problem Description Magina, also known as Anti-Mage, is a very cool hero in DotA (Defense of ...
- SpringSecurity的简单应用(一)
java项目首先要提的就是jar包了,Springsecurity的jar下载地址:http://static.springsource.org/spring-security/site/downlo ...
- SPRING IN ACTION 第4版笔记-第一章-003-AOP介绍
一.目标 要在BraveKnight调用embarkOnQuest()前后各做一些处理(调用Minstrel的方法) 二. 1.minstrel.xml <?xml version=" ...
- 设置VS2015上关闭和打开tab快捷键
Ctrl+W关闭Tab: Tools > Options > Environment > Keyboard > File.Close > Use new shortcut ...