zoukankan      html  css  js  c++  java
  • [React] Display Computed Data Using Recoil Selectors in React

    In this lesson, we're going to show how RecoilJS selectors are used to display computed data in React. While atoms are the go-to state objects in Recoil, selectors are the ideal choice when data can be computed based on existing state - like displaying the price of a restaurant order. And your selector output always remains up to date - just subscribe to it using one of the RecoilJS hooks.

     Define a 'atom':
    const order = atom({
      key: "order",
      default: ["garlic bread"] // on the house!
    });

    Use a atom:

    import { atom, useRecoilValue, selector } from "recoil";
    
      const myOrder = useRecoilValue(order);
    
      return (
        <div className="App">
          <h1>The Brunch Place</h1>
          {myOrder.map((food, i) => (
            <p key={i}>{food}</p>
          ))}
        </div>
      );

    Compute value based on state: using selector:

    import { atom, useRecoilValue, selector } from "recoil";
    
    const orderInfo = selector({
      key: "orderInfo",
      get: ({ get }) => {
        return {
          totalPrice: get(order)
            .map((food) => priceList[food])
            .reduce((current, sum) => current + sum, 0)
        };
      }
    });

    Use selector:

    const orderStats = useRecoilValue(orderInfo);
      <h4>Total Price: ${orderStats.totalPrice} </h4>

    Full code:

    import React from "react";
    import "./styles.css";
    import { atom, useRecoilValue, selector } from "recoil";
    
    const priceList = {
      coffee: 2,
      "garlic bread": 0,
      pancakes: 10
    };
    
    const order = atom({
      key: "order",
      default: ["garlic bread"] // on the house!
    });
    
    const orderInfo = selector({
      key: "orderInfo",
      get: ({ get }) => {
        return {
          totalPrice: get(order)
            .map((food) => priceList[food])
            .reduce((current, sum) => current + sum, 0)
        };
      }
    });
    
    export default function App() {
      const myOrder = useRecoilValue(order);
      const orderStats = useRecoilValue(orderInfo);
    
      return (
        <div className="App">
          <h1>The Brunch Place</h1>
          {myOrder.map((food, i) => (
            <p key={i}>{food}</p>
          ))}
          <h4>Total Price: ${orderStats.totalPrice} </h4>
        </div>
      );
    }
  • 相关阅读:
    c#基础问题笔记(一)
    自动化技术中的进给电气传动研习笔记2
    自动化技术中的进给电气传动研习笔记1
    汉字在电脑中是如何存储与编码的呢?
    三十分钟掌握STL
    python练习:函数2
    python练习:函数3
    Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form ResumeForm needs updating.
    vue 数组对象取对象的属性: Cannot read property 'xxxx' of undefined
    python练习:函数4
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13488392.html
Copyright © 2011-2022 走看看