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. 4071: [Apio2015]巴邻旁之桥

    Description 一条东西走向的穆西河将巴邻旁市一分为二,分割成了区域 A 和区域 B. 每一块区域沿着河岸都建了恰好 1000000001 栋的建筑,每条岸边的建筑都从 0 编号到 10000 ...

  2. Visual Studio Code扩展

    Visual Studio Code扩展 注:本文提到的代码示例下载地址>How to create a simple extension for VS Code VS Code 是微软推出的一 ...

  3. 记录一下MYSQL的SQL语法

    这是加时间的语法 update  mylog set  mydate= DATE_ADD( mydate, INTERVAL 13 HOUR) WHERE mydate BETWEEN '2014-0 ...

  4. C51 的编程规范

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

  5. Best Practices for Using Alpha

    Alpha是图形界面开发中常用的特效,通常我们会使用以下代码来实现Alpha特效: view.setAlpha(0.5f); View.ALPHA.set(view, 0.5f); ObjectAni ...

  6. PHP curl传输文件的版本兼容性

    /** * 存储文件到远程服务器 * * @param string $filePath * 文件绝对路径 * @param string $fileSaveUrl * 存储的远程目标地址 * @pa ...

  7. message 匹配不上grok正则 也会写入到elasticsearch

    { "message" => "scan test 20161201", "@version" => "1" ...

  8. 当函数没有return时错误

    error:control reaches end of non-void function 在对应函数+return   :  即可

  9. picturebox 图片自适应

    picturebox控件共有两种载入图片方式,分别为: pictureBox1.BackgroundImage = Image,pictureBox1.load(url) 为使加载的图片自使用控件尺寸 ...

  10. 【HDOJ】2844 Coins

    完全背包. #include <stdio.h> #include <string.h> ], c[]; int n, m; ]; int mymax(int a, int b ...