[Redux] Fetching Data on Route Change

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;
复制代码

 

posted @   Zhentiw  阅读(430)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示