[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‘)
);
时间: 2024-12-28 17:57:31

[Redux] Passing the Store Down Implicitly via Context的相关文章

前端(十):redux进阶之褪去react-redux的外衣

一.context实现数据传递 在react中,props和state都可以设置数据.不同的是,props借助组件属性传递数据但不可以渲染组件,它相对来说是“静态的”:state可以监听事件来修改数据并重新渲染组件,它相对来说是“动态的”.要想实现组件间传递数据并且可以根据state重新渲染组件,就必须一层层地传递props和this.state. redux借助context这个全局API,以及内置的getChildContext方法简化了数据传递.context是一个全局的变量,getChi

再探Redux Middleware

前言 在初步了解Redux中间件演变过程之后,继续研究Redux如何将中间件结合.上次将中间件与redux硬结合在一起确实有些难看,现在就一起看看Redux如何加持中间件. 中间件执行过程 希望借助图形能帮助各位更好的理解中间件的执行情况. redux如何加持中间件 现在是时候看看redux是如何将中间件结合了,我们在源码中一探究竟. * @param {Function} [enhancer] The store enhancer. You may optionally specify it

redux的使用

https://www.jianshu.com/p/7a6708cde333 安装:yarn add redux  react-redux --save redux分为三个部分组成action  reducer  store action可以触发reducer中的state   在改变共享状态的文件处使用 const { dispatch } = this.props;   //使用connect后会生成dispatch dispatch(switchMenu(title)); export c

Redux 和React 结合

当Redux 和React 相接合,就是使用Redux进行状态管理,使用React 开发页面UI.相比传统的html, 使用React 开发页面,确实带来了很多好处,组件化,代码复用,但是和Redux 接合时,组件化却也带来了一定的问题,组件层层嵌套,有成千上百个,而store确只有一个,组件中怎么才能获取到store?  页面UI就是显示应用程序状态的,如果获取不到store中的state, 那就没法渲染内容了.还有一个问题,就是如果状态发生了变化,组件怎么做到实时监听,实时显示最新的状态?

React: 研究React Redux的使用

一.简介 在上一篇的Redux文章中,详细介绍了Redux的概念和综合利用,开发者可以通过Redux的State管理系统管理整个应用程序的数据流,依靠功能完备的Store来分发Action,进而渲染和更新组件的UI.在我们之前的文章介绍中,根组件是保存State的组件,一般的Web开发,都是将State数据作为属性,从根组件向下传递给子组件,当子组件触发事件时,数据再通过回调函数的属性沿着组件树向上回到了根组件.这种数据在组件树中向上和向下传递的过程增加了程序的复杂性,于是乎,类似Redux的库

redux教程之源码解析createStore

redux源码 redux的源码很简单,分为以下几部分 createStore combineReducers applyMiddleware compose bindActionCreators createStore即入口函数生成store,将reducer和middleware关联起来 combineReducers即将分散的reducer最终合并成一个统一的reducer applyMiddleware即将多个中间件一次合并到reducer中,生成一个最终的reducer compose

redux+flux(一:入门篇)

React是facebook推出的js框架,React 本身只涉及UI层,如果搭建大型应用,必须搭配一个前端框架.也就是说,你至少要学两样东西,才能基本满足需要:React + 前端框架. Facebook官方使用的是 Flux 框架.本文就介绍如何在 React 的基础上,使用 Flux 组织代码和安排内部逻辑. 首先,Flux将一个应用分成四个部分: Flux 的最大特点,就是数据的"单向流动". 用户访问 View View 发出用户的 Action Dispatcher 收到

理解Javascript的状态容器Redux

Redux要解决什么问题? 随着 JavaScript 单页应用开发日趋复杂,JavaScript 需要管理比任何时候都要多的 state (状态). 这些 state 可能包括服务器响应.缓存数据.本地生成尚未持久化到服务器的数据,也包括 UI 状态,如激活的路由,被选中的标签,是否显示加载动效或者分页器等等.管理不断变化的 state 非常困难.如果一个 model 的变化会引起另一个 model 变化,那么当 view 变化时,就可能引起对应 model 以及另一个 model 的变化,依

Flux --&gt; Redux --&gt; Redux React 入门 基础实例使用

本文的目的很简单,介绍Redux相关概念用法 及其在React项目中的基本使用 假设你会一些ES6.会一些React.有看过Redux相关的文章,这篇入门小文应该能帮助你理一下相关的知识 一般来说,推荐使用 ES6+React+Webpack 的开发模式,但Webpack需要配置一些东西,你可以先略过,本文不需要Webpack基础 入门,只是一些基础概念和用法的整理,更完整的内容推荐去看看文档,英文,中文 (不过我个人认为,官方文档的例子相对来说太复杂了,很难让新手马上抓住重点) (官方的例子正