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. IRQL_NOT_LESS_OR_EQUAL的问题最终算攻克了

    今日想提高我那台古董笔记本extensa 4620Z的执行效率.方便我编程. 我先用万能的硬件检測工具,反正也就那几个流氓软件看了下.内存是ddr2的.我也顺带补习了一下许久不碰的硬件知识.ddr2和 ...

  2. 在VMware中为Linux系统安装VM-Tools的详解教程

    在安装Linux的虚拟机中,单击“虚拟机”菜单下的“安装Vmware-Tools”. 先介绍一下下面安装该工具时要用到的几个目录: /mnt 挂载目录,用来临时挂载别的文件系统,硬件设备 /tmp临时 ...

  3. 小学生之KTV播放原理

    第一步: 创建一个Song类 //歌曲名称 public  string SongName { get; set; } //歌曲路劲 public string SongPath { get; set ...

  4. 导出Exexcl类

    前台: <%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation=" ...

  5. iOS中你必须了解的多线程

    多线程概念详解 什么是进程? 简单的说进程就是我们电脑上运行的一个个应用程序,每一个程序就是一个进程,并且每个进程之间是独立的,每个进程运行在其专用受保护的内存空间内(window系统可以通过任务管理 ...

  6. js引用类型姿势

    栈 1)var a=new Array(),a.push(a,b,...),a.pop() queue 1)var a=new Array(), a.push(a,b,...),a.shift() a ...

  7. C# XmlSerializer序列化浅析

    C# 中使用 XmlSerializer 实现类和xml文件的序列化和反序列化,使用起来非常简单. C# XmlSerializer实现序列化: XmlSerializer xml = new Xml ...

  8. JS全部API笔记

    我相信对于程序猿都有做笔记的习惯. 我初学到现在也做了不少笔记,以前,总是怕写的文章或者好的内容分享出来就怕被直接copy以后更个名就不再是你的. 但通过博客园,学习到不少东西,人家都不怕什么了,我自 ...

  9. 使用inline-block做水平垂直居中

    父级宽高不定,如何使子元素水平垂直居中? 下面是用 display: inline-block 实现的: <!doctype html> <html lang="en&qu ...

  10. HTML&CSS基础学习笔记1-简单网页中有哪些标签?

    一个简单网页中有哪些HTML标签? 平时我们看到的网页,都是由HTML的标签来组成的.HTML标签非常多,我们先来认识一部分. 1. <html></html>称为根标签,所有 ...