项目作者: carlomartinucci

项目描述 :
useStateHistory custom hook for React 16.7.0-alpha.0 - next
高级语言: JavaScript
项目地址: git://github.com/carlomartinucci/use-state-history.git
创建时间: 2018-11-02T11:48:17Z
项目社区:https://github.com/carlomartinucci/use-state-history

开源协议:MIT License

下载


use-state-history

Motivation

If you use React Hooks, you may want an easy solution to handle not just the current state with useState, but also the history of the changes to that state, for instance with undo and redo functionality.

useStateHistory is a simple custom hook that gives you exactly that.

Getting Started

To get it started, add use-state-history to your project:

  1. npm install --save use-state-history

or

  1. yarn add use-state-history

Please note that use-state-history requires react@^16.7.0-alpha.0 as a peer dependency.

Examples

Basic Usage

  1. import React from 'react';
  2. import useStateHistory from 'use-state-history'
  3. function Counter() {
  4. const [count, setCount, { undo, redo }] = useStateHistory(0);
  5. return <div>
  6. <h1>Now: {count}</h1>
  7. <button onClick={() => setCount(count + 1)}> +1 </button>
  8. <button onClick={() => setCount(count - 1)}> -1 </button>
  9. <button onClick={() => setCount(0)}> => 0 </button>
  10. <button onClick={undo} disabled={!undo}> undo </button>
  11. <button onClick={redo} disabled={!redo}> redo </button>
  12. </div>;
  13. }

To visualize the history

  1. import React from 'react';
  2. import useStateHistory from 'use-state-history'
  3. function Counter() {
  4. const [count, setCount, { history, index, undo, redo }] = useStateHistory(0);
  5. return <div>
  6. <h1>Now: {count}</h1>
  7. <h2>History: {history.map((historyCount, currentIndex) => <span style={ currentIndex === index ? {color: 'red'} : null}>{historyCount} </span>)}</h2>
  8. <button onClick={() => setCount(count + 1)}> +1 </button>
  9. <button onClick={() => setCount(count - 1)}> -1 </button>
  10. <button onClick={() => setCount(0)}> => 0 </button>
  11. <button onClick={undo} disabled={!undo}> undo </button>
  12. <button onClick={redo} disabled={!redo}> redo </button>
  13. </div>;
  14. }

Implementation

useStateHistory is as simple as this:

  1. import { useState } from 'react';
  2. function useStateHistory(initialValue) {
  3. const [history, setHistory] = useState([initialValue])
  4. const [index, setIndex] = useState(0)
  5. const state = history[index]
  6. const setState = (newState) => {
  7. setHistory(history => history.slice(0, index + 1).concat(newState))
  8. setIndex(index => index + 1)
  9. }
  10. let undo, redo
  11. if (index > 0)
  12. undo = () => setIndex(index => index - 1)
  13. if (index < history.length - 1)
  14. redo = () => setIndex(index => index + 1)
  15. return [state, setState, { history, index, setHistory, setIndex, undo, redo }];
  16. }

License

MIT