[Redux] Extracting Container Components (FilterLink)
Learn how to avoid the boilerplate of passing the props down the intermediate components by introducing more container components.
Code to be refactored:
const FilterLink = ({
filter,
currentFilter,
children,
onClick
}) => {
if (filter === currentFilter) {
return <span>{children}</span>;
}
return (
<a href='#'
onClick={e => {
e.preventDefault();
onClick(filter);
}}
>
{children}
</a>
);
};
const Footer = ({
visibilityFilter,
onFilterClick
}) => (
<p>
Show:
{' '}
<FilterLink
filter='SHOW_ALL'
currentFilter={visibilityFilter}
onClick={onFilterClick}
>
All
</FilterLink>
{', '}
<FilterLink
filter='SHOW_ACTIVE'
currentFilter={visibilityFilter}
onClick={onFilterClick}
>
Active
</FilterLink>
{', '}
<FilterLink
filter='SHOW_COMPLETED'
currentFilter={visibilityFilter}
onClick={onFilterClick}
>
Completed
</FilterLink>
</p>
);
const TodoApp = ({
todos,
visibilityFilter
}) => (
<div>
...
...
...
<Footer
visibilityFilter={visibilityFilter}
onFilterClick={filter =>
store.dispatch({
type: 'SET_VISIBILITY_FILTER',
filter
})
}
/>
</div>
);
Notice in the container component, we pass visibilityFilter to the Footer presentional component, but Footer component actually doesn't do anything about that, just pass down to the FilterLink presentional component. This is the downside for the current approach.
TodoApp (C) --> Footer (P) --> FilterLink (P)
If we met this kind of problem, what we can do is, break FilterLink into:
FilterLink (C) --> Link (P)
We convent FilterLink into a container component and make a new presentional component called 'Link'.
And inside FilterLink, we can use Redux to getState(), everytime the state change, we force the component render itself and remember to unsubscribe when the component will unmount.
Also we move the dispatch action from TodoApp container component to the FilterLink container component. So that in TodoApp, the Footer component looks nice and clean.
So now, it looks like:
TodoApp (C) --> Footer (P) --> FilterLink (C) --> Link (P)
Link (P):
const Link = ({
active,
children,
onClick
}) => {
if (active) {
return <span>{children}</span>;
}
return (
<a href='#'
onClick={e => {
e.preventDefault();
onClick();
}}
>
{children}
</a>
);
};
FilterLink (C):
class FilterLink extends Component {
componentDidMount() {
this.unsubscribe = store.subscribe(() =>
this.forceUpdate()
);
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const props = this.props;
const state = store.getState();
return (
<Link
active={props.filter === state.visibilityFilter}
onClick={()=>{
store.dispatch({
type: 'SET_VISIBILITY_FILTER',
filter: props.filter
})
}}
>
{props.children}
</Link>
);
}
}
Footer (P):
const Footer = () => (
<p>
Show:
{' '}
<FilterLink
filter='SHOW_ALL'
>
All
</FilterLink>
{', '}
<FilterLink
filter='SHOW_ACTIVE'
>
Active
</FilterLink>
{', '}
<FilterLink
filter='SHOW_COMPLETED'
>
Completed
</FilterLink>
</p>
);
All:
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 { createStore } = Redux;
const store = createStore(todoApp);
const { Component } = React;
const Link = ({
active,
children,
onClick
}) => {
if (active) {
return <span>{children}</span>;
}
return (
<a href='#'
onClick={e => {
e.preventDefault();
onClick();
}}
>
{children}
</a>
);
};
class FilterLink extends Component {
componentDidMount() {
this.unsubscribe = store.subscribe(() =>
this.forceUpdate()
);
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const props = this.props;
const state = store.getState();
return (
<Link
active={props.filter === state.visibilityFilter}
onClick={()=>{
store.dispatch({
type: 'SET_VISIBILITY_FILTER',
filter: props.filter
})
}}
>
{props.children}
</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>
);
const AddTodo = ({
onAddClick
}) => {
let input;
return (
<div>
<input ref={node => {
input = node;
}} />
<button onClick={() => {
onAddClick(input.value);
input.value = '';
}}>
Add Todo
</button>
</div>
);
};
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
);
}
}
let nextTodoId = 0;
const TodoApp = ({
todos,
visibilityFilter
}) => (
<div>
<AddTodo
onAddClick={text =>
store.dispatch({
type: 'ADD_TODO',
id: nextTodoId++,
text
})
}
/>
<TodoList
todos={
getVisibleTodos(
todos,
visibilityFilter
)
}
onTodoClick={id =>
store.dispatch({
type: 'TOGGLE_TODO',
id
})
}
/>
<Footer />
</div>
);
const render = () => {
ReactDOM.render(
<TodoApp
{...store.getState()}
/>,
document.getElementById('root')
);
};
store.subscribe(render);
render();
[Redux] Extracting Container Components (FilterLink)的更多相关文章
- [Redux] Extracting Container Components -- Complete
Clean TodoApp Component, it doesn't need to receive any props from the top level component: const To ...
- [Redux] Extracting Container Components -- VisibleTodoList
Code to be refacted: const TodoList = ({ todos, onTodoClick }) => ( <ul> {todos.map(todo =& ...
- [Redux] Redux: Extracting Container Components -- AddTodo
Code to be refactored: const AddTodo = ({ onAddClick }) => { let input; return ( <div> < ...
- [Redux] Extracting Presentational Components -- Footer, FilterLink
Code to be refactored: let nextTodoId = 0; class TodoApp extends Component { render() { const { todo ...
- [Redux] Extracting Presentational Components -- AddTodo
The code to be refactored: let nextTodoId = 0; class TodoApp extends Component { render() { const { ...
- [Redux] Extracting Presentational Components -- TodoApp
Finally, I just noticed that the to-do app component doesn't actually have to be a class. I can turn ...
- [Redux] Extracting Presentational Components -- Todo, TodoList
Code to be refactored: let nextTodoId = 0; class TodoApp extends Component { render() { const { todo ...
- Presentational and Container Components
https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0 There’s a simple pattern I fi ...
- (翻译)React Container Components
原文:Container Components Container Components 在 React 模式上对我的代码有最深远影响的一个模式叫 container component 模式. 在 ...
随机推荐
- 零基础学习云计算及大数据DBA集群架构师【Linux系统\网络服务及安全配置2015年1月8日周五】
考试考一天,得分94,最后一题防火墙当时还没搞明白 考题如下: 注意事项: .确保在重启主机后所有配置仍然生效. .selinux 必须为Enforing 模式,防火墙必须开始.默认策略必须清空. . ...
- ASP.Net用jQuery ajax实现页面局部刷新
刚开始的时候使用asp的updatepanel控件实现局部刷新,而且在本地运行正确,但是部署到服务器上就变成整个页面全部刷新了.服务器用的是Windows server2000,本地机子上用的是win ...
- H3 BPM 笔记
先通过流程设计器设计流程 注意 审批:1个人 会签: 多人用 同意时: 若为有一个同意就通过 则 审批选项卡 的同意出口 设为1 如果需要所有人同意才通过 则 审批选项卡 的同意出口 设为100% ...
- SVN中trunk,branches,tags用法详解
原文地址:http://www.cnblogs.com/dafozhang/archive/2012/06/28/2567769.html Subversion有一个很标准的目录结构,是这样的.比如项 ...
- JQuery结合Ajax实现双击Table表格,使Table变成可编辑,并保存到数据库中
本文属于原创,转载请标明出处! 近期在做项目时,要实现通过双击Table表格的TR,使Table行变成可编辑,来实现修改数据并保存到数据库中的功能,无需多说,直接贴代码吧.希望能得到各位同仁指正. f ...
- ubuntu 安装RPM软件包
red hat 系统用rpm格式的文件安装软件,ubuntu安装软件是用deb格式的文件安装 在ubuntu上安装rmp文件格式的软件包步骤: 1.安装转换软件 alien(需要联网) apt-get ...
- (转)OS X 升級後 MacPorts 重新安裝筆記
原地址:http://blog.lyhdev.com/2012/07/os-x-macports.html Mac OS X 10.8 Mountain Lion 正式發佈,而且祭出台幣 $590 元 ...
- ZOJ3551 Bloodsucker(概率dp)
转载请注明出处: http://www.cnblogs.com/fraud/ ——by fraud Bloodsucker Time Limit: 2 Seconds Me ...
- 抽奖转盘(jqueryrotate.js)
jqueryrotate.js抽奖转盘,使用方便,兼容各浏览器,效果如下图 <!DOCTYPE> <head> <meta http-equiv="Conten ...
- 在PHP中PDO解决中文乱码问题
$this->pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => true)); $stmt = $th ...