Recoil_React

15632 ワード

定義#テイギ#

  • 状態管理ライブラリ
  • //atom 함수를 사용해서 생성
    const fontSizeState = atom({
        key: 'fontSizeState',
        default: 14,
    })
    
    const fontSizeLabelState = selector({
        key: 'fontSizeLabelState',
       //get속성은 계산될 함수
        get: ({get}) => {
          const fontSize = get(fontSizeState);
          const unit = 'px';
      
          return `${fontSize}${unit}`;
        },
      });
    
    const FontButton = () => {
        const [fontSize, setFontSize] = useRecoilState(fontSizeState);
        const fontSizeLabel = useRecoilValue(fontSizeLabelState);
    
        return (
            <>
                <div> font Size: ${fontSizeLabel}</div>
                <button onClick={() => setFontSize((size) => size + 1)} style={{fontSize}}>
                Enter
                </button>
            </>
        );
    }
    両親の木に<RecoilRoot></RecoilRoot>で包む

    atoms

  • は更新および購読可能であり、共有状態であり、ステータスは
  • である.
  • には、一意の鍵(重複しない)
  • が必要です.
  • は、任意の要素において、
  • と読み書きすることができる.
  • atom値を読み出す構成部品のデフォルト購読atom
  • したがってatomに変化がある場合、その要素を購読するすべての要素は
  • 再レンダリングされます.

    selecters

  • 原子状態値
  • を同期または非同期で変換する.
  • 原子または他のセレクタを入力として受け入れる純関数
  • の親の原子またはセレクタが更新されると、子のセレクタ関数も
  • を再実行します.
  • 構成部品は、原子のようにセレクタを購読することができ、セレクタを変更すると、構成部品も
  • で再レンダリングされます.
  • は最小の状態セットのみを原子に格納、他の派生データはすべてセレクタで指定する関数によって有効に計算され、無駄な状態が保持されないようにする
  • .
  • セレクタとatomsは同じインタフェースを有し、
  • を互いに置き換えることができる.
  • セレクタ関数を使用して定義された
  • UserRecoilValue()を使用して、
  • を読み込むことができます.

    TodoList

    function TodoItem({item}) {
      const [todoList, setTodoList] = useRecoilState(todoListState);
      const index = todoList.findIndex((listItem) => listItem === item);
    
      const editItemText = ({target: {value}}) => {
        const newList = replaceItemAtIndex(todoList, index, {
          ...item,
          text: value,
        });
    
        setTodoList(newList);
      };
    
      const toggleItemCompletion = () => {
        const newList = replaceItemAtIndex(todoList, index, {
          ...item,
          isComplete: !item.isComplete,
        });
    
        setTodoList(newList);
      };
    
      const deleteItem = () => {
        const newList = removeItemAtIndex(todoList, index);
    
        setTodoList(newList);
      };
    
      return (
        <div>
          <input type="text" value={item.text} onChange={editItemText} />
          <input
            type="checkbox"
            checked={item.isComplete}
            onChange={toggleItemCompletion}
          />
          <button onClick={deleteItem}>X</button>
        </div>
      );
    }
    
    function replaceItemAtIndex(arr, index, newValue) {
      return [...arr.slice(0, index), newValue, ...arr.slice(index + 1)];
    }
    
    function removeItemAtIndex(arr, index) {
      return [...arr.slice(0, index), ...arr.slice(index + 1)];
    }