zoukankan      html  css  js  c++  java
  • [Recoil] Use selectorFamily to take arguments in your Recoil selectors

    In this lesson, we're going to learn how to create Recoil selectors that accept arguments. These are made possible using the selectorFamily utility function.

    We'll start with an existing application that uses a regular selector to display a sorted array of Todo items, and then we'll refactor it so that we're able to supply the sort type (ascending or descending) in the React component itself.

    For more information on selectorFamily, have a look at the official RecoilJS docs: https://recoiljs.org/docs/api-reference/utils/selectorFamily

    Similar to 'selector', 'selectorFamily' is more functional approach, allow to pass additional parameters to 'get' & 'set' functions.

    import React from "react";
    import "./styles.css";
    import { atom, selectorFamily, useRecoilValue } from "recoil";
    import { DateTime } from "luxon";
    
    const currentTime = DateTime.local();
    
    const sortedTodoList = selectorFamily({
      key: "sortedTodoList",
      get: (sortedType) => ({ get }) => {
        const todos = get(todoList);
    
        return sortedType === "ASC"
          ? todos.sort((a, b) => a.createdAt - b.createdAt)
          : todos.sort((a, b) => b.createdAt - a.createdAt);
      }
    });
    
    const todoList = atom({
      key: "todoList",
      default: [
        {
          name: "buy milk",
          createdAt: currentTime
        },
        {
          name: "write a book",
          createdAt: currentTime.plus({ days: 1 })
        },
        {
          name: "do some exercise",
          createdAt: currentTime.plus({ days: 2 })
        }
      ]
    });
    
    export default function App() {
      const sortOrder = "DESC";
      const mySortedTodoList = useRecoilValue(sortedTodoList(sortOrder));
    
      return (
        <div className="App">
          <h1>Todo List</h1>
          {mySortedTodoList.map((item, index) => (
            <p key={index}>
              {item.name} - {item.createdAt.toISODate()}
            </p>
          ))}
        </div>
      );
    }
  • 相关阅读:
    月薪3万+的大数据人都在疯学Flink,为什么?
    Flink应用场景
    Flink生态与未来
    flink学习笔记-split & select(拆分流)
    .NET MVC5简介(四)Filter和AuthorizeAttribute权限验证
    .NET MVC5简介(三)Result
    .NET MVC5简介(二)
    VUE基础实用技巧
    .NET MVC5简介(一)
    WebApi简介
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13640876.html
Copyright © 2011-2022 走看看