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. slivelight5和数据库交互

    最近开始研究sliverlight和数据库交互了,无奈网上资料较少,查阅了大量资料终于成功了,但是我记得还有别的方法,希望大家讨论一下 数据访问层我的用的是ado.net实体数据模型 然后新建了一个w ...

  2. NET Portability Analyzer

    NET Portability Analyzer 分析迁移dotnet core 大多数开发人员更喜欢一次性编写好业务逻辑代码,以后再重用这些代码.与构建不同的应用以面向多个平台相比,这种方法更加容易 ...

  3. 安装app到Simulator

    1.安装brew 打开命令行,执行以下命令: ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install ...

  4. [原博客] POI系列(1)

    正规.严谨.精妙. -POI 发现POI(波兰信息学奥赛)的题都很有意思.于是开刷bzoj上的poi题目(按ac人数降序..).顺手写一写题解,加深印象. 为了防止一篇文章过于长,打算每五道题另起一篇 ...

  5. Html5 跨域通信

    H5 跨域通信: 在主页面中通过iframe嵌入外部页面,通过iframe的window对象postMessage方法向iframe页面传递消息. 1 <!DOCTYPE html> 2 ...

  6. 算法练习之:Doubles

    Doubles Time Limit: 1000MS Memory Limit: 65536KB Problem Description As part of an arithmetic compet ...

  7. 基于Maven的spring_security入门

    配置文件的修改点没什么变化,可以参考:http://blog.csdn.net/ouitiken/article/details/8830505 pom.xml的依赖参考: <dependenc ...

  8. *[hackerrank]Tree Covering

    https://www.hackerrank.com/contests/illuminati/challenges/tree-covering 这道题先是在上次交流讨论了一下,然后两位百度的朋友先写完 ...

  9. C51 的编程规范

    编程首要是要考虑程序的可行性,然后是可读性.可移植性.健壮性以及可测试性.这是总则.但是很多人忽略了可读性.可移植性和健壮性(可调试的方法可能歌不相同),这是不对的. 1.当项目比较大时,最好分模块编 ...

  10. 【Xamarin 跨平台机制原理剖析】

    原文:[Xamarin 跨平台机制原理剖析] [看了请推荐,推荐满100后,将发补丁地址] Xamarin项目从喊口号到现在,好几个年头了,在内地没有火起来,原因无非有三,1.授权费贵 2.贵 3.原 ...