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>
      );
    }
  • 相关阅读:
    [LeetCode]10. Regular Expression Matching
    [LeetCode]9. Palindrome Number
    [LeetCode]8. String to Integer (atoi)
    javascript 内部函数的定义及调用
    canvas和白鹭引擎中平移,旋转,缩放
    改变this指向的call,apply,bind方法
    关于JavaScript中this小有理解
    关于位运算符的计算法方法
    制作简单的GIF动图
    HTML中的单位小结
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13640876.html
Copyright © 2011-2022 走看看