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>
      );
    }
  • 相关阅读:
    crontab
    待重写
    待重写
    多套开发资源使用情况
    待重写
    待重写
    待重写
    docker安装es
    docker run启动时目录映射研究
    rabbitmq第二篇:使用插件实现延迟功能
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13640876.html
Copyright © 2011-2022 走看看