[Redux] Generating Containers with connect() from React Redux (FooterLink)
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)的更多相关文章
- [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 ...
- [Redux] Generating Containers with connect() from React Redux (AddTodo)
Code to be refacted: const AddTodo = (props, { store }) => { let input; return ( <div> < ...
- 使用react+redux+react-redux+react-router+axios+scss技术栈从0到1开发一个applist应用
先看效果图 github地址 github仓库 在线访问 初始化项目 #创建项目 create-react-app applist #如果没有安装create-react-app的话,先安装 npm ...
- React Redux Sever Rendering实战
# React Redux Sever Rendering(Isomorphic JavaScript) connect、applyMiddleware、thunk、webpackHotMiddleware
今天,我们通过解读官方示例代码(counter)的方式来学习react+redux. 例子 这个例子是官方的例子,计数器程序.前两个按钮是加减,第三个是如果当前数字是奇数则加一,第四个按钮是异步加一( ...
- react+redux教程(五)异步、单一state树结构、componentWillReceiveProps
今天,我们要讲解的是异步.单一state树结构.componentWillReceiveProps这三个知识点. 例子 这个例子是官方的例子,主要是从Reddit中请求新闻列表来显示,可以切换reac ...
- react+redux教程(四)undo、devtools、router
上节课,我们介绍了一些es6的新语法:react+redux教程(三)reduce().filter().map().some().every()....展开属性 今天我们通过解读redux-undo ...
- react+redux+generation-modation脚手架添加一个todolist
当我遇到问题: 要沉着冷静. 要管理好时间. 别被bug或error搞的不高兴,要高兴,又有煅炼思维的机会了. 要思考这是为什么? 要搞清楚问题的本质. 要探究问题,探究数据的流动. TodoList ...
- 实例讲解基于 React+Redux 的前端开发流程
原文地址:https://segmentfault.com/a/1190000005356568 前言:在当下的前端界,react 和 redux 发展得如火如荼,react 在 github 的 s ...
随机推荐
- struts2——简单登陆实例
从今天开始,一起跟 各位聊聊java的三大框架——SSH.先从Struts开始说起,Struts对MVC进行了很好的封装,使用Struts的目的是为了帮助我们减少在 运用MVC设计模型来开发Web应用 ...
- Oracle 学习笔记 19 -- 触发器和包浅析(PL/SQL)
触发器是存放在数据库中的一种特殊类型的子程序.不能被用户直接调用,而是当特定事件或操作发生时由系统自己主动 调用执行.触发器不能接受參数.所以执行触发器就叫做触发或点火.Oracle事件指的是数据库的 ...
- UITabBar背景、icon图标颜色、被选中背景设置以及隐藏UITabBar的两种方式
一.对UITabBar背景和icon图标的一些设置 (1)因为直接给UITabBar设置的背景颜色显示的不纯,半透明的感觉,所以,有时候我们可以直接利用纯色的图片作为背景达到想要的效果: (2)给ic ...
- Asp.net开发常用的51个非常实用的代码
1.弹出对话框.点击转向指定页面 Code: Response.Write("<script>window.alert('该会员没有提交申请,请重新提交!')</scrip ...
- SQLServer 跨服务器查询的两个办法
网上搜了跨服务器查询的办法,大概就是Linked Server(预存连接方式并保证连接能力)和OpenDataSource(写在语句中,可移植性强).根据使用函数的不同,性能差别显而易见...虽然很简 ...
- django的Model 模型中常用的字段类型
常用的字段类型: AutoField:自增长字段,通常不用,如果未在Model中显示指定主键,django会默认建立一个整型的自增长主键字段 BooleanField:布尔型,值为True或False ...
- XtraReport改变纸张方向
XtraReport纸张方向改变可以通过修改Landscape属性: Landscape=true 为横向输出 Landscape=false 为纵向输出
- POJ 2135 Farm Tour (最小费用最大流模板)
题目大意: 给你一个n个农场,有m条道路,起点是1号农场,终点是n号农场,现在要求从1走到n,再从n走到1,要求不走重复路径,求最短路径长度. 算法讨论: 最小费用最大流.我们可以这样建模:既然要求不 ...
- 数值的N次方
问题描述: 实现函数double Power(double base,int exponent),求base的exponent次方.不得使用库函数, 同时不需考虑大数问题. 思路分析: 要是你秒秒钟想 ...
- 使用JavaScript判断图片是否加载完成的三种实现方式
有时需要获取图片的尺寸,这需要在图片加载完成以后才可以.有三种方式实现,下面一一介绍. 一.load事件 <!DOCTYPE HTML> <html> <head> ...