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. Docker入门

    -----------------------------------------Docker入门教程(一)介绍Docker入门教程(二)命令Docker入门教程(三)DockerFileDocker ...

  2. python学习之--自定义函数:

    Python之--自定义函数: 在Python中,定义一个函数要使用def语句,依次写出函数名.括号.括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回. 以下自定义 ...

  3. Android使用Dom解析xml

    一.理论准备                 二.上代码  <?xml version="1.0" encoding="utf-8" ?> < ...

  4. 李洪强漫谈iOS开发[C语言-028]-逗号表达式

  5. VS2008编译器编译出来的文件比mingw编译的要几乎小一半

    为什么要在VS2008中使用QT静态编译呢?很简单,因为VS2008编译器编译出来的文件比mingw编译的要几乎小一半. 好了现在我们来做些准备工作,VS2008自然要安装的,然后打上SP1的补丁.然 ...

  6. Android 你应该知道的学习资源 进阶之路贵在坚持

    1.国外教程网站 Android Developers Blog 不解释 vogella 很不错的网站,免费的,包含android的教程也比较全面,并且教程中经常引用大牛blog,会有很多意外发现.代 ...

  7. android使用tabhost实现导航

    参考 http://blog.csdn.net/xixinyan/article/details/6771341 http://blog.sina.com.cn/s/blog_6b04c8eb0101 ...

  8. bzoj3875

    悲伤地回忆,当初写了一个作死的算法爆零了为什么不好好写暴力呢……显然设w[i]表示彻底干掉这个怪物的代价注意发现这里的转移具有后效性,但是干掉每个怪物的最优值是一定的我们用spfa来转移,详见那篇sp ...

  9. easyui-lang-zh_CN.js导入后还是英文提示

    <script src="/js/easyUI1.3.3/jquery.easyui.min.js" type="text/javascript"> ...

  10. DBA的那些事

    --Author:Leshami --Blog    :http://blog.csdn.ne/leshami 说起DBA,全称是Database Administrator,不是Doctor of ...