zoukankan      html  css  js  c++  java
  • [React Recoil] Use selectors to calculate derived data based on state stored within a Recoil atom

    Recoil allows us to use atoms in order to store pieces of state. More often than not in our apps we need to use data that derives from our application state (for instance to multiply height and width stored within a state to calculate area of an element).

    Luckily Recoil provides us with a powerful tool to automatically re-calculate derived state value whenever an piece of state changes - selectors.

    selector is a pure function that accepts atoms or other selectors as input. When these upstream atoms or selectors are updated, the selector function will be re-evaluated.

    In this quick lesson we're going to learn how to use a selector in order to automatically calculate a square of a number whenever a value stored within an atom is going to change

      
    import React from "react";
    import {
      RecoilRoot,
      atom,
      selector,
      useRecoilState,
      useRecoilValue,
    } from "recoil";
    import "./App.css";
    
    const numState = atom({
      key: "numState",
      default: 0,
    });
    
    const squareState = selector({
      key: "squareState",
      get: ({ get }) => {
        return get(numState) ** 2;
      },
    });
    
    function Counter() {
      const [number, setNumber] = useRecoilState(
        numState
      );
    
      return (
        <button
          onClick={() => setNumber(number + 1)}
        >
          Increment!
        </button>
      );
    }
    
    function Square() {
      const squareNumber = useRecoilValue(
        squareState
      );
      return <div>Square: {squareNumber}</div>;
    }
    
    function Display() {
      const number = useRecoilValue(numState);
      return <div>Number: {number}</div>;
    }
    
    function App() {
      return (
        <RecoilRoot>
          <div className="App">
            <h1>Recoil!</h1>
            <Counter />
            <Display />
            <Square />
          </div>
        </RecoilRoot>
      );
    }
    
    export default App;
  • 相关阅读:
    IP和MAC
    ASCII,Unicode 和 UTF-8
    php(PHP Hypertext Preprocessor)随笔1
    css层叠样式表 (Cascading Style Sheets)初识
    ansible部署
    mysql三种备份方式
    nginx反向代理,负载均衡,动静分离,rewrite地址重写介绍
    Maven安装和配置
    jenkins之Tomcat7+jdk1.7+jenkins
    CentOS 7.0如何安装配置iptables和seLinux以及firewalld
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12901763.html
Copyright © 2011-2022 走看看