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的更多相关文章

  1. [Redux] Passing the Store Down with <Provider> from React Redux

    Previously, we wrote the Provider component by ourself: class Provider extends Component { getChildC ...

  2. [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 ...

  3. 如何优雅的设计Redux中的Store

    用了几个月的redux,现在回过来总结一下. 刚开始用的时候遇到一个比较大的疑问,就是如何设计redux的store中的state树,这应该是我在使用redux中最大的一个疑问,阻挡了我前进的脚步,当 ...

  4. Redux API之Store

    Store Store 就是用来维持应用所有的 state 树 的一个对象. 改变 store 内 state 的惟一途径是对它 dispatch 一个action. Store 不是类.它只是有几个 ...

  5. 动手实现 React-redux(二):结合 context 和 store

    既然要把 store 和 context 结合起来,我们就先构建 store.在 src/index.js 加入之前创建的 createStore 函数,并且构建一个 themeReducer 来生成 ...

  6. 【React】Redux入门 & store体验

    组件间传值联动是令人头疼的问题,尤其是一个组件影响多个其他组件状态变化的时候,常常需要一级一级与父组件传值,与父组件的兄弟组件传值等等, 如何化繁为简地处理‘牵一发动全身’的清理就是将所有组件的sta ...

  7. 使用react Context+useReducer替代redux

    首先明确一点,Redux 是一个有用的架构,但不是非用不可.事实上,大多数情况,你可以不用它,只用 React 就够了. 曾经有人说过这样一句话. "如果你不知道是否需要 Redux,那就是 ...

  8. 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. ...

  9. 详解 Node + Redux + MongoDB 实现 Todolist

    前言 为什么要使用 Redux? 组件化的开发思想解放了繁琐低效的 DOM 操作,以 React 来说,一切皆为状态,通过状态可以控制视图的变化,然后随着应用项目的规模的不断扩大和应用功能的不断丰富, ...

随机推荐

  1. using namespace cocos2d;

    忘记在头文件添加using namespace cocos2d; 导致一直出现问题,定义的精灵却一直报错. error C2143: 语法错误 : 缺少“;”(在“*”的前面)

  2. J2EE (十) 简洁的JSTL、EL

    简介 JSTL(JSP Standard Tag Library ,JSP标准标签库)是一个不断完善的开放源代码的JSP标签库. 由四个定制标记库(core.format.xml 和 sql)和一对通 ...

  3. Ubuntu网络管理

    1.重启NetworkManager service network-manager stop rm /var/lib/NetworkManager/NetworkManager.state serv ...

  4. HID 报告描述符精细说明.

    1,报告描述符概述    1.1) 报表描述符        报表描述符和USB的其他描述符是不一样的,它不是一个简单的表格,报表描述符是USB所有描述符中最复杂的.报表描述符非常复杂而有弹性,因为它 ...

  5. CentOS6.X 系统安装图文教程,超详细

    http://www.myhack58.com/Article/sort099/sort0102/2011/32363_7.htm

  6. Spinner( 微调) 组件

    本节课重点了解 EasyUI 中 Spinner(微调)组件的使用方法,这个组件依赖于ValidateBox(验证框)组件. 一. 加载方式Spinner(微调)组件是其他两款高级微调组件的基础组件, ...

  7. Resharper

    http://baike.baidu.com/link?url=H8DVtrvKV1Cg-Hrz82C6ZiJOUXbi_3BfoROe-RlHhctPna4-BFfglPh2OsR-KmCqRZ7_ ...

  8. MVC路由规则以及前后台获取Action、Controller、ID名方法

    1.前后台获取Action.Controller.ID名方法 前台页面:ViewContext.RouteData.Values["Action"].ToString(); Vie ...

  9. js基本类型

    1.undefined 1)var a;//没有赋值的时候就是undefined 2)undefined派生自null,alert(undefined==null)//true 虽然这上条语句是一样, ...

  10. 使用PyQt4写界面后台程序方法总结

    使用PyQt4编写界面后台程序的方法总结 一.怎么建立多线程 界面程序如果有稍微耗时一点的任务如果不使用多线程就会界面卡死,所以大多数情况会使用到多线程.PyQt4自己有多线程的机制,可以派生多线程类 ...