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))
    }
  • 相关阅读:
    8.02_python_lx_day14
    8.02_python_lx_day13<2>
    8.02_python_lx_day13<1>
    7.30_python_lx_day20
    7.29_python_lx_da19
    7.29_python_lx_day12
    Docker镜像
    Docker学习Ⅱ
    Docker学习Ⅰ
    2-3树的插入和删除原理
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10731851.html
Copyright © 2011-2022 走看看