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的更多相关文章

  1. Part 39 AngularJS route change events

    In this video we will discuss1. Different events that are triggered when a route change occurs in an ...

  2. 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 ...

  3. Fetching data with Ajax小例子

    ajax获取数据示例: 示例1 通过ajax获取txt文件里面的内容示例: <html> <head> <title>Ajax at work</title& ...

  4. [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 ...

  5. 『奇葩问题集锦』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安装的根目 ...

  6. Kafka消费者拉取数据异常Unexpected error code 2 while fetching data

    Kafka消费程序间歇性报同一个错: 上网没查到相关资料,只好自己分析.通过进一步分析日志发现,只有在拉取某一个特定的topic的数据时报错,如果拉取其他topic的数据则不会报错.而从这个异常信息来 ...

  7. 使用 empApi 组件实现 Change Data Capture 功能

    Change Data Capture 功能是从 Winter '19 版本开始正式启用的功能. 它是基于"发布-订阅"模式设计,可以将 Salesforce 中记录的改变自动推送 ...

  8. [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 ...

  9. [Redux] Important things in Redux

    Root Smart component can be overloaded, divide 'smart' component wisely & using Provider. Proble ...

随机推荐

  1. 个人学习笔记--MyBatis官方推荐DAO开发方案

    1.导入Jar包 2.编写全局配置文件configuration.xml <?xml version="1.0" encoding="UTF-8" ?&g ...

  2. 第 7 章 门面模式【Facade Pattern】

    以下内容出自:<<24种设计模式介绍与6大设计原则>> 好,我们继续讲课.大家都是高智商的人,都写过纸质的信件吧,比如给女朋友写情书什么的,写信的过程大家都还记得吧,先写信的内 ...

  3. django开发总结:

    一,关于setting目录中的“DEBUG” DEBUG=False 把DEBUG从True改成False后就会出现(必需指定404和500错语页面,如上图的目录结构)找不到页面的错误.原因是DEBU ...

  4. bzoj 1914: [Usaco2010 OPen]Triangle Counting 数三角形 容斥

    1914: [Usaco2010 OPen]Triangle Counting 数三角形 Time Limit: 10 Sec  Memory Limit: 64 MBSubmit: 272  Sol ...

  5. VLAN间单臂路由访问

    实验书上的拓朴图: 注意TRUNK端口和路由器子端口设置,可以承载不同的VLAN标签. 交换机(用2691加交换模块实现的): Building configuration... Current co ...

  6. CycleScrollView实现轮播图

    // //  CycleScrollView.h //  PagedScrollView // //  Created by 李洪强 on 16-1-23. //  Copyright (c) 201 ...

  7. VirtualBox虚拟机中启用usb3.0却无法显示u盘的解决方法

    主机系统为win7 64位,由于工作需要,安装了Virtualbox 5.18虚拟机,virtaulbox中安装了win7 32系统.以为下启用usb 3.0的步骤: 1.宿主机要支持 usb 3.0 ...

  8. git支持中文

    以前使用git,都要参考这个来进行中文支持 http://blog.csdn.net/son_of_god/article/details/7341928 有一次更新了git之后,发现默认支持了中文[ ...

  9. EditPlus+MinGW搭建简易的C/C++开发环境

    EditPlus+MinGW搭建简易的C/C++开发环境 有时候想用C编点小程序,但是每次都要启动那难用又难看的VC实在是不情愿,而且老是会生成很多没用的中间文件,很讨厌,后来看到网上有很多人用Edi ...

  10. mybatis源码分析(3)——SqlSessionManager类

    从上图可能看出,在 mybatis中,SqlSession的实现类有两个,其中SqlSessionManager类不但实现了SqlSession接口,同时也实现了SqlSessionFactory接口 ...