[Redux] Generating Containers with connect() from React Redux (FooterLink)
Code to be refactored:
- 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
- };
First to create mapStateToProps, It is fairly common to use the container props when calculating the child props, so this is why props are passed as a second argument:
- const mapStateToLinkProps = (
- state,
- ownProps
- ) => {
- return {
- active: ownProps.filter === state.visibilityFilter
- }
- }
Second, we need to write mapDispatchToProp function:
- const mapDispatchToLinkProps = (
- dispatch,
- ownProps
- ) => {
- return {
- onClick: () => {
- dispatch({
- type: 'SET_VISIBILITY_FILTER',
- filter: ownProps.filter
- })
- }
- }
- }
Last, we need to create connect function, point to the Link compoment:
- const FilterLink = connect(mapStateToLinkProps, mapDispatchToLinkProps)(Link);
We can now use the filter link container component and specify just the filter, but the underlying link component will have received the calculated active and on-click values.
-------------
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,
- onClick,
- children,
- }) => {
- if (active) {
- return <span>{children}</span>;
- }
- return (
- <a href='#'
- onClick={e => {
- e.preventDefault();
- onClick();
- }}
- >
- {children}
- </a>
- );
- };
- const { connect } = ReactRedux;
- const mapStateToLinkProps = (
- state,
- ownProps
- ) => {
- return {
- active: ownProps.filter === state.visibilityFilter
- }
- }
- const mapDispatchToLinkProps = (
- dispatch,
- ownProps
- ) => {
- return {
- onClick: () => {
- dispatch({
- type: 'SET_VISIBILITY_FILTER',
- filter: ownProps.filter
- })
- }
- }
- }
- const FilterLink = connect(mapStateToLinkProps, mapDispatchToLinkProps)(Link);
- 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;
- let AddTodo = ({ dispatch }) => {
- let input;
- return (
- <div>
- <input ref={node => {
- input = node;
- }} />
- <button onClick={() => {
- dispatch({
- type: 'ADD_TODO',
- id: nextTodoId++,
- text: input.value
- })
- input.value = '';
- }}>
- Add Todo
- </button>
- </div>
- );
- };
- AddTodo = connect()(AddTodo);
- 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
- );
- }
- }
- const mapStateToTodoListProps = (state) => {
- return {
- todos: getVisibleTodos(
- state.todos,
- state.visibilityFilter
- )
- };
- };
- const mapDispatchToTodoListProps = (dispatch) => {
- return {
- onTodoClick: (id) => {
- dispatch({
- type: 'TOGGLE_TODO',
- id
- });
- }
- };
- };
- const VisibleTodoList = connect(
- mapStateToTodoListProps,
- mapDispatchToTodoListProps
- )(TodoList);
- const TodoApp = () => (
- <div>
- <AddTodo />
- <VisibleTodoList />
- <Footer />
- </div>
- );
- const { Provider } = ReactRedux;
- const { createStore } = Redux;
- ReactDOM.render(
- <Provider store={createStore(todoApp)}>
- <TodoApp />
- </Provider>,
- document.getElementById('root')
- );
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>JS Bin</title>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.0.4/redux.js"></script>
- <script src="https://fb.me/react-0.14.0.js"></script>
- <script src="https://fb.me/react-dom-0.14.0.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/4.0.0/react-redux.js"></script>
- </head>
- <body>
- <div id='root'></div>
- </body>
- </html>
[Redux] Generating Containers with connect() from React Redux (FooterLink)的更多相关文章
- [Redux] Generating Containers with connect() from React Redux (VisibleTodoList)
Learn how to use the that comes with React Redux instead of the hand-rolled implementation from the ...
- [Redux] Generating Containers with connect() from React Redux (AddTodo)
Code to be refacted: const AddTodo = (props, { store }) => { let input; return ( <div> < ...
- 使用react+redux+react-redux+react-router+axios+scss技术栈从0到1开发一个applist应用
先看效果图 github地址 github仓库 在线访问 初始化项目 #创建项目 create-react-app applist #如果没有安装create-react-app的话,先安装 npm ...
- React Redux Sever Rendering实战
# React Redux Sever Rendering(Isomorphic JavaScript) connect、applyMiddleware、thunk、webpackHotMiddleware
今天,我们通过解读官方示例代码(counter)的方式来学习react+redux. 例子 这个例子是官方的例子,计数器程序.前两个按钮是加减,第三个是如果当前数字是奇数则加一,第四个按钮是异步加一( ...
- react+redux教程(五)异步、单一state树结构、componentWillReceiveProps
今天,我们要讲解的是异步.单一state树结构.componentWillReceiveProps这三个知识点. 例子 这个例子是官方的例子,主要是从Reddit中请求新闻列表来显示,可以切换reac ...
- react+redux教程(四)undo、devtools、router
上节课,我们介绍了一些es6的新语法:react+redux教程(三)reduce().filter().map().some().every()....展开属性 今天我们通过解读redux-undo ...
- react+redux+generation-modation脚手架添加一个todolist
当我遇到问题: 要沉着冷静. 要管理好时间. 别被bug或error搞的不高兴,要高兴,又有煅炼思维的机会了. 要思考这是为什么? 要搞清楚问题的本质. 要探究问题,探究数据的流动. TodoList ...
- 实例讲解基于 React+Redux 的前端开发流程
原文地址:https://segmentfault.com/a/1190000005356568 前言:在当下的前端界,react 和 redux 发展得如火如荼,react 在 github 的 s ...
随机推荐
- 使用SqlCacheDependency依赖项让数据库变化后缓存失效
SqlCacheDependency可以使缓存在数据库或者数据库某张表或者字段变化后让指定缓存失效.对于一些需要及时显示的信息比较有用. 需要.net2.0以后设sql server2005及以后版本 ...
- Javascript进阶篇——浏览器对象—Location、Navigator、userAgent、screen对象
Location对象location用于获取或设置窗体的URL,并且可以用于解析URL.语法: location.[属性|方法] location对象属性图示: location 对象属性: loca ...
- 利用MetaWeblog API 自制博客发布小工具
博客园提供了诸多数据接口, 利用这些接口可以很容易的实现博客的发布,修改,删除等 1.需要引用一个DLL:为CookComputing.XmlRpcV2 2.新建一个类,在其中是一些要实现的东西,如: ...
- 基础命名空间:反射 using System.Reflection
反射概念: .Net的应用程序由几个部分:‘程序集(Assembly)’.‘模块(Module)’.‘类型(class)’组成,程序集包含模块 模块包含类型,类型又包含 成员,而反射提供一 ...
- AFNetWorking 关于manager.requestSerializer.timeoutInterval 不起作用的问题
之前一直遇到关于AFNetWorking请求时间设置了但是不起作用的情况,现用如下方式设置AF的超市时间即可. [manager.requestSerializer willChangeValueFo ...
- Gengxin讲STL系列——Set
本系列第二篇blog 第一篇写的心潮澎湃,结果写完一看,这都是些什么玩意= =| Set的中文名称是“集合”.集合,高一数学必修一课本给出的定义已经很明确了,简单来讲就是一个不含重复元素的空间(个人定 ...
- C语言enum再学习
通常来说我们使用enum是这样的: enum week{ Mon, Tue, ... Sun }; enum week w; w = Mon; 这里默认Mon~Sun的值为0~6 也可以自己定值 , ...
- poj1623 Squadtrees
转载请注明出处: http://www.cnblogs.com/fraud/ ——by fraud 需要求出按题目要求建四叉树所需的结点个数,和压缩后的四叉树的结点个数(压缩即只要将 ...
- vim 折叠技巧
转自:http://www.2cto.com/os/201203/122133.html 主要命令: zf-创建折叠 zf20G--创建折叠,从当前行折叠到第20行 zfgg--创建折叠,从当前位置折 ...
- 用git提交代码步骤
1.git add XXXX2.git commit - 'xxx'3.git stash4. //git pull --rebase 4. git rebase origin/develop git ...