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. Xcode7.01相对于底版本的变动小结

    1.在Xcode7中系统不再自动支持http请求,需要配置plist才能使用http: 2.appdelegate中的self.window不再支持直接往window上加view,必须先给window ...

  2. 实战 SSH 端口转发

    转自实战 SSH 端口转发 通过本文的介绍,读者可以从中了解到如何应用 SSH 端口转发机制来解决日常工作 / 生活中的一些问题.学会在非安全环境下使用端口转发来加密网络应用,保护个人隐私以及重要商业 ...

  3. 【BZOJ 3110】 [Zjoi2013]K大数查询(整体二分)

    [题目] Description 有N个位置,M个操作.操作有两种,每次操作如果是1 a b c的形式表示在第a个位置到第b个位置,每个位置加入一个数c如果是2 a b c形式,表示询问从第a个位置到 ...

  4. AFN演示

  5. sqlite的源代码加密,以及其它一些文章

    一.       给数据库加密 前面所说的内容网上已经有很多资料,虽然比较零散,但是花点时间也还是可以找到的.现在要说的这个——数据库加密,资料就很难找.也可能是我操作水平不够,找不到对应资料.但不管 ...

  6. git图示所有分支的历史

    1.第一种方法 git gui 菜单栏上 repository-->visual all branch history 或者直接使用命令gitk --all 2.在git bash中,使用命令查 ...

  7. BZOJ1831: [AHOI2008]逆序对

    1831: [AHOI2008]逆序对 Time Limit: 10 Sec  Memory Limit: 64 MBSubmit: 341  Solved: 226[Submit][Status] ...

  8. IIS短文件漏洞修复

    近期网站系统被扫描出漏洞:IIS短文件/文件夹漏洞 漏洞级别:中危漏洞 漏洞地址:全网站 漏洞描述:IIS短文件名泄露漏洞,IIS上实现上存在文件枚举漏洞,攻击者可利用此漏洞枚举获取服务器根目录中的文 ...

  9. Linux文件虚拟机系统只读Read-only file system的快速解决方法

    问题描述:上周公司的私有云(底层架构是Openstack+KVM,目前稳定性还不够好,开发团队在改进中)一个计算节点挂掉,之后恢复后发现这个计算节点的所有Linux系统都变成只读了,复制文件提示:Re ...

  10. 在net安装程序中部署oracle客户端全攻略

    在net安装程序中部署oracle客户端全攻略 主要的是要做三件工作: 打包文件,写注册表,注册环境变量说明:我的oracle版本为9, 在2000 advanced server 上测试通过,可以正 ...