Code to be refactored:

class FilterLink extends Component {
componentDidMount() {
const { store } = this.context;
this.unsubscribe = store.subscribe(() =>
this.forceUpdate()
);
} componentWillUnmount() {
this.unsubscribe();
} render() {
const props = this.props;
const { store } = this.context;
const state = store.getState(); return (
<Link
active={
props.filter ===
state.visibilityFilter
}
onClick={() =>
store.dispatch({
type: 'SET_VISIBILITY_FILTER',
filter: props.filter
})
}
>
{props.children}
</Link>
);
}
}
FilterLink.contextTypes = {
store: React.PropTypes.object
};

First to create mapStateToProps, It is fairly common to use the container props when calculating the child props, so this is why props are passed as a second argument:

const mapStateToLinkProps = (
state,
ownProps
) => {
return {
active: ownProps.filter === state.visibilityFilter
}
}

Second, we need to write mapDispatchToProp function:

const mapDispatchToLinkProps = (
dispatch,
ownProps
) => {
return {
onClick: () => {
dispatch({
type: 'SET_VISIBILITY_FILTER',
filter: ownProps.filter
})
}
}
}

Last, we need to create connect function, point to the Link compoment:

const FilterLink = connect(mapStateToLinkProps, mapDispatchToLinkProps)(Link);

We can now use the filter link container component and specify just the filter, but the underlying link component will have received the calculated active and on-click values.

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

Code:

const todo = (state, action) => {
switch (action.type) {
case 'ADD_TODO':
return {
id: action.id,
text: action.text,
completed: false
};
case 'TOGGLE_TODO':
if (state.id !== action.id) {
return state;
} return {
...state,
completed: !state.completed
};
default:
return state;
}
}; const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
todo(undefined, action)
];
case 'TOGGLE_TODO':
return state.map(t =>
todo(t, action)
);
default:
return state;
}
}; const visibilityFilter = (
state = 'SHOW_ALL',
action
) => {
switch (action.type) {
case 'SET_VISIBILITY_FILTER':
return action.filter;
default:
return state;
}
}; const { combineReducers } = Redux;
const todoApp = combineReducers({
todos,
visibilityFilter
}); const { Component } = React; const Link = ({
active,
onClick,
children,
}) => {
if (active) {
return <span>{children}</span>;
} return (
<a href='#'
onClick={e => {
e.preventDefault();
onClick();
}}
>
{children}
</a>
);
}; const { connect } = ReactRedux;
const mapStateToLinkProps = (
state,
ownProps
) => {
return {
active: ownProps.filter === state.visibilityFilter
}
} const mapDispatchToLinkProps = (
dispatch,
ownProps
) => {
return {
onClick: () => {
dispatch({
type: 'SET_VISIBILITY_FILTER',
filter: ownProps.filter
})
}
}
} const FilterLink = connect(mapStateToLinkProps, mapDispatchToLinkProps)(Link); const Footer = () => (
<p>
Show:
{' '}
<FilterLink filter='SHOW_ALL'>
All
</FilterLink>
{', '}
<FilterLink filter='SHOW_ACTIVE'>
Active
</FilterLink>
{', '}
<FilterLink filter='SHOW_COMPLETED'>
Completed
</FilterLink>
</p>
); const Todo = ({
onClick,
completed,
text
}) => (
<li
onClick={onClick}
style={{
textDecoration:
completed ?
'line-through' :
'none'
}}
>
{text}
</li>
); const TodoList = ({
todos,
onTodoClick
}) => (
<ul>
{todos.map(todo =>
<Todo
key={todo.id}
{...todo}
onClick={() => onTodoClick(todo.id)}
/>
)}
</ul>
); let nextTodoId = 0;
let AddTodo = ({ dispatch }) => {
let input; return (
<div>
<input ref={node => {
input = node;
}} />
<button onClick={() => {
dispatch({
type: 'ADD_TODO',
id: nextTodoId++,
text: input.value
})
input.value = '';
}}>
Add Todo
</button>
</div>
);
};
AddTodo = connect()(AddTodo); const getVisibleTodos = (
todos,
filter
) => {
switch (filter) {
case 'SHOW_ALL':
return todos;
case 'SHOW_COMPLETED':
return todos.filter(
t => t.completed
);
case 'SHOW_ACTIVE':
return todos.filter(
t => !t.completed
);
}
} const mapStateToTodoListProps = (state) => {
return {
todos: getVisibleTodos(
state.todos,
state.visibilityFilter
)
};
}; const mapDispatchToTodoListProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch({
type: 'TOGGLE_TODO',
id
});
}
};
}; const VisibleTodoList = connect(
mapStateToTodoListProps,
mapDispatchToTodoListProps
)(TodoList); const TodoApp = () => (
<div>
<AddTodo />
<VisibleTodoList />
<Footer />
</div>
); const { Provider } = ReactRedux;
const { createStore } = Redux; ReactDOM.render(
<Provider store={createStore(todoApp)}>
<TodoApp />
</Provider>,
document.getElementById('root')
);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.0.4/redux.js"></script>
<script src="https://fb.me/react-0.14.0.js"></script>
<script src="https://fb.me/react-dom-0.14.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/4.0.0/react-redux.js"></script>
</head>
<body>
<div id='root'></div>
</body>
</html>

[Redux] Generating Containers with connect() from React Redux (FooterLink)的更多相关文章

  1. [Redux] Generating Containers with connect() from React Redux (VisibleTodoList)

    Learn how to use the that comes with React Redux instead of the hand-rolled implementation from the ...

  2. [Redux] Generating Containers with connect() from React Redux (AddTodo)

    Code to be refacted: const AddTodo = (props, { store }) => { let input; return ( <div> < ...

  3. 使用react+redux+react-redux+react-router+axios+scss技术栈从0到1开发一个applist应用

    先看效果图 github地址 github仓库 在线访问 初始化项目 #创建项目 create-react-app applist #如果没有安装create-react-app的话,先安装 npm ...

  4. React Redux Sever Rendering实战

    # React Redux Sever Rendering(Isomorphic JavaScript) ![React Redux Sever Rendering(Isomorphic)入门](ht ...

  5. react+redux教程(一)connect、applyMiddleware、thunk、webpackHotMiddleware

    今天,我们通过解读官方示例代码(counter)的方式来学习react+redux. 例子 这个例子是官方的例子,计数器程序.前两个按钮是加减,第三个是如果当前数字是奇数则加一,第四个按钮是异步加一( ...

  6. react+redux教程(五)异步、单一state树结构、componentWillReceiveProps

    今天,我们要讲解的是异步.单一state树结构.componentWillReceiveProps这三个知识点. 例子 这个例子是官方的例子,主要是从Reddit中请求新闻列表来显示,可以切换reac ...

  7. react+redux教程(四)undo、devtools、router

    上节课,我们介绍了一些es6的新语法:react+redux教程(三)reduce().filter().map().some().every()....展开属性 今天我们通过解读redux-undo ...

  8. react+redux+generation-modation脚手架添加一个todolist

    当我遇到问题: 要沉着冷静. 要管理好时间. 别被bug或error搞的不高兴,要高兴,又有煅炼思维的机会了. 要思考这是为什么? 要搞清楚问题的本质. 要探究问题,探究数据的流动. TodoList ...

  9. 实例讲解基于 React+Redux 的前端开发流程

    原文地址:https://segmentfault.com/a/1190000005356568 前言:在当下的前端界,react 和 redux 发展得如火如荼,react 在 github 的 s ...

随机推荐

  1. java项目获取路径的几种方式

    第一种: File f = new File(this.getClass().getResource("/").getPath()); System.out.println(f); ...

  2. 集合操作出现的ConcurrentModificationException(源码分析)

    摘要: 为了保证线程安全,在迭代器迭代的过程中,线程是不能对集合本身进行操作(修改,删除,增加)的,否则会抛出ConcurrentModificationException的异常. 示例: publi ...

  3. Qwerty78 Trip(组合数,规律,逆元)

    Qwerty78 Trip time limit per test 2 seconds memory limit per test 64 megabytes input standard input ...

  4. LR选择哪种方式录制

    LR选择哪种方式录制,有以下考虑原则: 1.基于浏览器的应用程序推荐使用HTML-basic script方式录制 2.不是基于浏览器的应用程序推荐使用URL-basic script方式录制 3.如 ...

  5. Hacker(十一)----黑客常用入侵方法

    Internet中,为了防止黑客入侵自己的电脑,就必须了解黑客入侵目标计算机的常用方法.黑客常用的入侵方法有数据驱动攻击.系统文件非法利用.伪造信息攻击.远端操纵等. 一.数据驱动攻击 数据驱动攻击是 ...

  6. Android学习笔记--广播(Broadcast)

    1.Android广播分类 android的广播类型分为两类:标准广播和有序广播. 标准广播:异步广播,广播发出后,所有注册了的广播接收器都会同时接收到该广播.打个比方:做地铁过程中的语音播报,当列车 ...

  7. 关于scrollTop

    如下图

  8. ResourceBundle读取中文properties文件问题

    昨天遇到一个问题,用ResourceBundle读取中文字符串资源文件时,死活读不出来. 一开始以为是文件路径不对,后来发现如果默认properties文件时英文就没问题.我的项目代码是在src目录下 ...

  9. 一些不熟悉的SQL脚本--约束条件

    1.根据表名查询主键的SQL语句 SELECT D.COLUMN_NAME AS COLNAME FROM USER_CONS_COLUMNS D, USER_CONSTRAINTS M WHERE ...

  10. nginx启动报错(1113: No mapping for the Unicode character exists in the target multi-byte code page)

    使用windows版本的nginx启动时遇到(1113: No mapping for the Unicode character exists in the target multi-byte co ...