[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 way, using the advanced React feature called context.
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')
);
I'm creating a new component called provider. From its render method, it just returns whatever its child is. We can wrap any component in a provider, and it's going to render that component.
I'm changing the render call to render a to-do app inside the provider. I'm moving this tool prop from the to-do app to the provider component. The provider component will use the React advanced context feature to make this chore available to any component inside it, including grandchildren.
To do this, it has to define a special method get child context that will be called by React by using this props tool which corresponds to this chore that is passed to the provider as a prop just once.
class Provider extends Component {
getChildContext() {
return {
store: this.props.store
};
} render() {
return this.props.children;
}
}
Provider.childContextTypes = {
store: React.PropTypes.object
}; const { createStore } = Redux; ReactDOM.render(
<Provider store={createStore(todoApp)}>
<TodoApp />
</Provider>,
document.getElementById('root')
);
Remember to define 'childContextTypes', if not it won't work.
Then we go to refactor the 'VisibleTodoList' class Component:
class VisibleTodoList 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 (
<TodoList
todos={
getVisibleTodos(
state.todos,
state.visibilityFilter
)
}
onTodoClick={id =>
store.dispatch({
type: 'TOGGLE_TODO',
id
})
}
/>
);
}
} VisibleTodoList.contextTypes = {
store: React.PropTypes.object
};
The same as 'Footer' Class Component:
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
};
Then 'AddTodo' functional component, it doesn't have 'this' keyword, but we still able to get the 'context' from the second arguement.
let nextTodoId = 0;
const AddTodo = (props, { 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>
);
}; AddTodo.contextTypes = {
store: React.PropTypes.object
};
----------------------
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,
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.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
}; 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;
const AddTodo = (props, { 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>
);
};
AddTodo.contextTypes = {
store: React.PropTypes.object
}; 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.context;
this.unsubscribe = store.subscribe(() =>
this.forceUpdate()
);
} componentWillUnmount() {
this.unsubscribe();
} render() {
const props = this.props;
const { store } = this.context;
const state = store.getState(); return (
<TodoList
todos={
getVisibleTodos(
state.todos,
state.visibilityFilter
)
}
onTodoClick={id =>
store.dispatch({
type: 'TOGGLE_TODO',
id
})
}
/>
);
}
}
VisibleTodoList.contextTypes = {
store: React.PropTypes.object
}; const TodoApp = () => (
<div>
<AddTodo />
<VisibleTodoList />
<Footer />
</div>
); class Provider extends Component {
getChildContext() {
return {
store: this.props.store
};
} render() {
return this.props.children;
}
}
Provider.childContextTypes = {
store: React.PropTypes.object
}; const { createStore } = Redux; ReactDOM.render(
<Provider store={createStore(todoApp)}>
<TodoApp />
</Provider>,
document.getElementById('root')
);
[Redux] Passing the Store Down Implicitly via Context的更多相关文章
- [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 Explicitly via Props
n the previous lessons, we used this tool to up level variable to refer to the Redux chore. The comp ...
- 如何优雅的设计Redux中的Store
用了几个月的redux,现在回过来总结一下. 刚开始用的时候遇到一个比较大的疑问,就是如何设计redux的store中的state树,这应该是我在使用redux中最大的一个疑问,阻挡了我前进的脚步,当 ...
- Redux API之Store
Store Store 就是用来维持应用所有的 state 树 的一个对象. 改变 store 内 state 的惟一途径是对它 dispatch 一个action. Store 不是类.它只是有几个 ...
- 动手实现 React-redux(二):结合 context 和 store
既然要把 store 和 context 结合起来,我们就先构建 store.在 src/index.js 加入之前创建的 createStore 函数,并且构建一个 themeReducer 来生成 ...
- 【React】Redux入门 & store体验
组件间传值联动是令人头疼的问题,尤其是一个组件影响多个其他组件状态变化的时候,常常需要一级一级与父组件传值,与父组件的兄弟组件传值等等, 如何化繁为简地处理‘牵一发动全身’的清理就是将所有组件的sta ...
- 使用react Context+useReducer替代redux
首先明确一点,Redux 是一个有用的架构,但不是非用不可.事实上,大多数情况,你可以不用它,只用 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. ...
- 详解 Node + Redux + MongoDB 实现 Todolist
前言 为什么要使用 Redux? 组件化的开发思想解放了繁琐低效的 DOM 操作,以 React 来说,一切皆为状态,通过状态可以控制视图的变化,然后随着应用项目的规模的不断扩大和应用功能的不断丰富, ...
随机推荐
- 好看的Select下拉框是如何制造的
现在在大多数网站中都能看到很华丽的Select下拉框,他们是如何实现的呢?使用默认select肯定是不好实现,我们可以使用div+js去模拟出来select的功能,并且又能很简单的去美化它. CSS代 ...
- (二)《Java编程思想》——t h i s 关键字
this 关键字(注意只能在方法内部使用)可为已调用了其方法的那个对象生成相应的句柄.可象对待其他任何对象句柄一样对待这个句柄. package chapter4; //: Leaf.java // ...
- 封装Socket.BeginReceive/EndReceive支持Timeout简介
.NET中的Socket类提供了网络通信常用的方法,分别提供了同步和异步两个版本,其中异步的实现是基于APM异步模式实现,即BeginXXX/EndXXX的方式.异步方法由于其非阻塞的特性,在需考虑程 ...
- NHibernate之映射文件配置说明(转载1)
源博客:http://www.cnblogs.com/kissdodog/archive/2013/02/21/2919886.html 1. hibernate-mapping 这个元素包括以下可选 ...
- [c#]asp.net开发微信公众平台(5)微信图文消息
上篇已经成功响应了关注事件,也实现了文本消息的发送,这篇开始图文消息处理, 微信中最常用的消息类型就是图文消息了,因为它图文并茂,最能表达信息. 图文消息在微信中的接口定义如下: <xml> ...
- ref和out与SQL中的output
什么时候会需要使用ref和out 有时,我们会需要获取某个值在方法中的运行状态,根据定义的方法,我们仅仅能够获得一个返回值,但是,有时我们也许想获取多个值,通过返回值就不能返回这样的信息,我们可以通过 ...
- 使用jQuery操作元素的属性与样式
本文学习如何使用jQuery获取和操作元素的属性和CSS样式. 元素属性和Dom属性 对于下面这样一个标签元素: <img id='img' src="1.jpg" alt= ...
- cas+tomcat+shiro实现单点登录-4-Apache Shiro 集成Cas作为cas client端实现
目录 1.tomcat添加https安全协议 2.下载cas server端部署到tomcat上 3.CAS服务器深入配置(连接MYSQL) 4.Apache Shiro 集成Cas作为cas cli ...
- OpenCV——识别手写体数字
这个是树莓派上运行的, opencv3 opencv提供了一张手写数字图片给我们,如下图所示,可以作为识别手写数字的样本库. 0到9共十个数字,每个数字有五行,一行100个数字.首先要把这5000个数 ...
- DX笔记之五------游戏画面绘图之绘制位图
本系列文章由zhmxy555编写,转载请注明出处. http://blog.csdn.net/zhmxy555/article/details/7335103 共四步 步骤一:加载位图 步骤二:建立与 ...