We will learn how to use withRouter() to inject params provided by React Router into connected components deep in the tree without passing them down all the way down as props.

The app component itself does not really use filter. It just passes the filter down to the visible todo list, which uses it to calculate the currently visible todos. Passing the params from the top level of route handlers gets tedious, so I'm removing the filter prop. Instead, I'm going to find a way to read the current router params in the visible todo list itself.

App.js:

import React from 'react';
import Footer from './Footer';
import AddTodo from './AddTodo';
import VisibleTodoList from './VisibleTodoList';

const App = () => (
  <div>
    <AddTodo />
    <VisibleTodoList/>
    <Footer />
  </div>
);

export default App;

I will add a new import code with Router from the React Router package. It's important that we use at least React Router 3.0 for it to work well with Redux. With Router, it takes a React component and returns a different React component that injects the router-related props, such as params, into your component.

//VisibleTodoList.js

import {withRouter} from 'react-router';

I want the params to be available inside mapStateToProps, so I need to wrap the connect result so that the connected component gets the params as a prop. I can scroll up a little bit to the mapStateToProps definition and I can change it so that, rather than read filter directly from ownProps, it's going to read it from ownProps.params.

const mapStateToProps = (state, ownProps) => {
  return {
    todos: getVisibleTodos(state.todos, ownProps.params.filter || 'all'), // if filter is '' then change to 'all'
  };
};

..

const VisibleTodoList = withRouter(connect(
    mapStateToProps,
    mapDispatchToProps
)(TodoList));

----------------

So instead let router params passed down from the App,  we just let visibleTodoList to get router params by using withRouter. withRouter will inject the params inside router to the props.

import {connect} from 'react-redux';
import {toggleTodo} from '../actions';
import TodoList from './TodoList';
import {withRouter} from 'react-router';

const getVisibleTodos = (todos, filter) => {
    switch (filter) {
        case 'all':
            return todos;
        case 'completed':
            return todos.filter(t => t.completed);
        case 'active':
            return todos.filter(t => !t.completed);
        default:
            throw new Error(`Unknown filter: ${filter}.`);
    }
};

const mapStateToProps = (state, {params}) => {
    return {
        todos: getVisibleTodos(state.todos, params.filter || 'all'), // if filter is '' then change to 'all'
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        onTodoClick: (id) => {
            dispatch(toggleTodo(id));
        },
    };
};

const VisibleTodoList = withRouter(connect(
    mapStateToProps,
    mapDispatchToProps
)(TodoList));

export default VisibleTodoList;

[Redux] Using withRouter() to Inject the Params into Connected Components的更多相关文章

  1. [Redux] Important things in Redux

    Root Smart component can be overloaded, divide 'smart' component wisely & using Provider. Proble ...

  2. react脚手架改造(react/react-router/redux/eslint/karam/immutable/es6/webpack/Redux DevTools)

    公司突然组织需要重新搭建一个基于node的论坛系统,前端采用react,上网找了一些脚手架,或多或少不能满足自己的需求,最终在基于YeoMan的react脚手架generator-react-webp ...

  3. 【译】Redux 还是 Mobx,让我来解决你的困惑!

    原文地址:Redux or MobX: An attempt to dissolve the Confusion 原文作者:rwieruch 我在去年大量的使用了 Redux,但我最近都在使用 Mob ...

  4. React + Redux 入坑指南

    Redux 原理 1. 单一数据源 all states ==>Store 随着组件的复杂度上升(包括交互逻辑和业务逻辑),数据来源逐渐混乱,导致组件内部数据调用十分复杂,会产生数据冗余或者混用 ...

  5. redux基础(1)

    redux ps:每个案例都是接着上一个案例写的 主要以案例讲解如何使用,具体概念请参考如下: 基本概念参考1 基本概念参考2 案例源码戳这里 一.Store.Action.Reducer简介 Sto ...

  6. [Preact] Integrate react-router with Preact

    React-router is the community favourite routing solution - it can handle all of your complex routing ...

  7. 记一次改造react脚手架的过程

    公司突然组织需要重新搭建一个基于node的论坛系统,前端采用react,上网找了一些脚手架,或多或少不能满足自己的需求,最终在基于YeoMan的react脚手架generator-react-webp ...

  8. knockoutjs扩展与使用

    原来考虑使用avalon2.0 经过一周的试验,能力不够,用不起来.最终使用了knockout-3.4.js <!DOCTYPE html> <html> <head&g ...

  9. Unity3D核心类型一览

    Unity3D核心类型一览 本文记录了Unity3D的最基本的核心类型.包括Object.GameObject.Component.Transform.Behaviour.Renderer.Colli ...

随机推荐

  1. 【Codeforces163E】e-Government AC自动机fail树 + DFS序 + 树状数组

    E. e-Government time limit per test:1 second memory limit per test:256 megabytes input:standard inpu ...

  2. QT的信号和槽

    QObject::connect(&dummy, SIGNAL(sig()), &thread, SLOT(slot_main())); 这里slot_main()是thread类中的 ...

  3. json 与jsonp 特点及区别

    简单描述JSON跟JSONP的区别以及实战 什么是JSON? 前面简单说了一下,JSON是一种基于文本的数据交换方式,或者叫做数据描述格式,你是否该选用他首先肯定要关注它所拥有的优点. JSON的优点 ...

  4. Round函数

    Round():函数返回一个数值,舍入到指定的长度或精度 eg: --1) ) ---->123.9990 ) ---->124.0000 --3为需要舍入的位数 --2) ) ----- ...

  5. sencha动态向容器里添加控件出现重叠问题

    sencha动态向容器里添加控件出现重叠问题原因是由于动态生成控件的id有重复导致的.(js取时间到毫秒来做id,放在for里面会出现几个控件id是相同的情况.).解决掉重复id的问题就好了. 版权声 ...

  6. CREATEINPUTLAYOUT_INCOMPATIBLEFORMAT

    这个error的全称是这样的 D3D11 ERROR: ID3D11Device::CreateInputLayout: Element[1]'s format (UNKNOW) cannot be ...

  7. SQLite的SQL语法

    SQLite库能够解析大部分标准SQL语言.但它也省去了一些特性而且增加了一些自己的新特性.这篇文档就是试图描写叙述那些SQLite支持/不支持的SQL语法的.查看keyword列表. 例如以下语法表 ...

  8. HTTP 请求报文 响应报文(转)

    引言 超文本传输协议(HTTP,HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议.所有的WWW文件都必须遵守这个标准.设计HTTP最初的目的是为了提供一种发 ...

  9. 解决多个py模块调用同一个python的logging模块,打印日志冲突问题

    前期对python中的logging模块进行了封装,这样自动化测试框架中的多个测试脚本(py)就可以使用同一个封装后的日志系统,这样各脚本中只需要引用一下即可,方面快捷.那么当我使用unittest框 ...

  10. Python爬虫基础之UrlError

    一.urllib.error python的urllib.error模块主要是应对urllib.request在网络请求过程中出现的异常而定义的异常处理类.主要有URLError和HTTPError两 ...