zoukankan      html  css  js  c++  java
  • [Functional Programming] Using Lens to update nested object

    For example, in React application, we have initial state;

    const data = {
        nextId: 4,
        todoFilter: 'SHOW_ALL',
        todos: [
            { id: 1, title: 'Hug Unicorn', completed: false },
            { id: 2, title: 'Mess with Texas', completed: false },
            { id: 3, title: 'Do Laundry', completed: true }
        ],
        ui: {
            filterGroups: {
                status: false
            }
        }
    }

    We have a toggle button, which everytime, it is toggle 'ui.filterGroups.status' to true/false.

    Whenever we have to update nested object, we should always comes up a word 'Lens'!

    Here is how to do it:

    import { State, compose  } from 'crocks'
    import {lensPath, lensProp, over, not} from 'ramda'
    const { modify } = State
    
    // ui -> filterGroups -> status
    
    const lnsFilterGroups = lensPath(['ui', 'filterGroups'])
    export const toggleFilterGroup = ({ group }) => {
        const lns = compose(
            lnsFilterGroups,
            lensProp(group)
        )
    
        return modify(over(lns, not))
    }
  • 相关阅读:
    关于编码的问题(转)
    XML巩固
    浏览器兼容问题的解决方案
    JavaScript 全局变量命名空间生成函数
    表格的使用(转)
    post上传文件
    安装cocoapods
    UILabel内容模糊
    动态获取键盘高度
    iOS多线程同步锁
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10731851.html
Copyright © 2011-2022 走看看