[Redux] Passing the Store Down Explicitly via Props
n the previous lessons, we used this tool to up level variable to refer to the Redux chore. The components that access this chore, such as the container components, read this straight from it, subscribe to this chore, and dispatch actions on this chore using this chore top-level variable.
This approach works fine for JS bin example where everything is in a single file. However, it doesn't scale to real applications for several reasons.
First of all, it makes your container components harder to test because they reference a specific chore, but you might want to supply a different marks chore in the test. Secondly, it makes it very hard to implement universal replications that are rendered on the server, because on the server, you want to supply a different chore instance for every request because different requests have different data.
Every container component needs a reference to this chore so unfortunately, we have to pass it down to every component as a prop. It's less effort than passing different data through every component, but it's still inconvenient. So, don't worry, we'll find a better solution later, but for now, we need to see the problem.
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,
children,
onClick
}) => {
if (active) {
return <span>{children}</span>;
}
return (
<a href='#'
onClick={e => {
e.preventDefault();
onClick();
}}
>
{children}
</a>
);
};
class FilterLink extends Component {
componentDidMount() {
const { store } = this.props;
this.unsubscribe = store.subscribe(() =>
this.forceUpdate()
);
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const props = this.props;
const { store } = 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 = ({ store }) => (
<p>
Show:
{' '}
<FilterLink
filter='SHOW_ALL'
store={store}
>
All
</FilterLink>
{', '}
<FilterLink
filter='SHOW_ACTIVE'
store={store}
>
Active
</FilterLink>
{', '}
<FilterLink
filter='SHOW_COMPLETED'
store={store}
>
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;
const AddTodo = ({ store }) => {
let input;
return (
<div>
<input ref={node => {
input = node;
}} />
<button onClick={() => {
store.dispatch({
type: 'ADD_TODO',
id: nextTodoId++,
text: 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
);
}
}
class VisibleTodoList extends Component {
componentDidMount() {
const { store } = this.props;
this.unsubscribe = store.subscribe(() =>
this.forceUpdate()
);
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const props = this.props;
const { store } = props;
const state = store.getState();
return (
<TodoList
todos={
getVisibleTodos(
state.todos,
state.visibilityFilter
)
}
onTodoClick={id =>
store.dispatch({
type: 'TOGGLE_TODO',
id
})
}
/>
);
}
}
const TodoApp = ({ store }) => (
<div>
<AddTodo store={store} />
<VisibleTodoList store={store} />
<Footer store={store} />
</div>
);
const { createStore } = Redux;
ReactDOM.render(
<TodoApp store={createStore(todoApp)} />,
document.getElementById('root')
);
[Redux] Passing the Store Down Explicitly via Props的更多相关文章
- [Redux] Passing the Store Down with <Provider> from React Redux
Previously, we wrote the Provider component by ourself: class Provider extends Component { getChildC ...
- [Redux] Passing the Store Down Implicitly via Context
We have to write a lot of boiler plate code to pass this chore down as a prop. But there is another ...
- 如何优雅的设计Redux中的Store
用了几个月的redux,现在回过来总结一下. 刚开始用的时候遇到一个比较大的疑问,就是如何设计redux的store中的state树,这应该是我在使用redux中最大的一个疑问,阻挡了我前进的脚步,当 ...
- Redux API之Store
Store Store 就是用来维持应用所有的 state 树 的一个对象. 改变 store 内 state 的惟一途径是对它 dispatch 一个action. Store 不是类.它只是有几个 ...
- 【React】Redux入门 & store体验
组件间传值联动是令人头疼的问题,尤其是一个组件影响多个其他组件状态变化的时候,常常需要一级一级与父组件传值,与父组件的兄弟组件传值等等, 如何化繁为简地处理‘牵一发动全身’的清理就是将所有组件的sta ...
- Redux 源码解读 —— 从源码开始学 Redux
已经快一年没有碰过 React 全家桶了,最近换了个项目组要用到 React 技术栈,所以最近又复习了一下:捡起旧知识的同时又有了一些新的收获,在这里作文以记之. 在阅读文章之前,最好已经知道如何使用 ...
- react+redux教程(一)connect、applyMiddleware、thunk、webpackHotMiddleware
今天,我们通过解读官方示例代码(counter)的方式来学习react+redux. 例子 这个例子是官方的例子,计数器程序.前两个按钮是加减,第三个是如果当前数字是奇数则加一,第四个按钮是异步加一( ...
- redux介绍与入门
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 20.0px Helvetica } p.p2 { margin: 0.0px 0.0px 0.0px 0. ...
- 看漫画,学 Redux
Flux 架构已然让人觉得有些迷惑,而比 Flux 更让人摸不着头脑的是 Flux 与 Redux 的区别.Redux 是一个基于 Flux 思想的新架构方式,本文将探讨它们的区别. 如果你还没有看过 ...
随机推荐
- Win2 Socket(套接字)相关 API
Socket(套接字) 作者信息 肖进 单位:南京中萃食品有限公司 资讯部 邮箱:xiaoj@njb.swirebev.com 电话:025-58642091 与socket有关的一些函数介绍 1.读 ...
- Selenium2学习之-环境搭建
1.下载安装Eclipse 2.下载并配置jdk环境变量 2.1 介绍一下环境变量设置 2.1.1 点击环境变量 2.1.2 新增系统变量JAVA_HOME 变量名:JAVA_HOME 变量值:C:\ ...
- 学习Android NestedScroll
NestedScrollingChildHelper 这是一个用于实现子视图嵌套滚动的辅助类,并提供对Android 5.0之前版本的前兼容. View要作为嵌套滚动中的Child,要在构造方法中实例 ...
- Visual Studio 2015开发Android App问题集锦
Visual Studio 2015开发Android App 启动调试始终无法完成应用部署的解决方案 创建一个Android App项目后,直接启动调试发现Visual Studio Emulato ...
- Oracle—用户管理的备份(一)
用户管理的备份(一) 一.首先要知道数据库中表空间和文件的信息,有几个性能视图,v$datafile,v$tablespace,v$tempfile,v$logfile,v$controlfile,d ...
- include,include_once,require,require_once的区别
1.include,require在其被调用的位置处包含一个文件. 2.include_once,require_once函数的作用与include相同,不过它会首先验证是否已包含该文件.如果已经包含 ...
- MongoDB 介绍及Windows下安装
一.MongoDB简介 MongoDB是一个高性能,开源,无模式的文档型数据库,是当前NoSql数据库中比较热门的一种.它在许多场景下可用于替代传统的关系型数据库或键/值存储方式.Mongo使用C++ ...
- jQuery自学笔记(三):jQuery动画效果
jQuery隐藏和显示: 使用 hide( ) 和 show( ) 方法来隐藏和显示 HTML 元素: 语法: $(selector).hide(speed,callback); $(selector ...
- (转载)C# 编程 使用可空类型
转载出处为://https://msdn.microsoft.com/zh-cn/library/2cf62fcy(vs.90).aspx#Anchor_1 C#可以为 null 的类型可以表示基础类 ...
- 容器 vector :为何要有reserve
关于STL容器,最令人称赞的特性之一就是是只要不超过它们的最大大小,它们就可以自动增长到足以容纳你放进去的数据.(要知道这个最大值,只要调用名叫max_size的成员函数.)对于vector和stri ...