库地址

https://github.com/jamiebuilds/unstated-next#migration-from-unstated

安装方式

  1. npm install --save unstated-next

示例代码

  1. import React, { useState } from "react"
  2. import { createContainer } from "unstated-next"
  3. import { render } from "react-dom"
  4. function useCounter(initialState = 0) {
  5. let [count, setCount] = useState(initialState)
  6. let decrement = () => setCount(count - 1)
  7. let increment = () => setCount(count + 1)
  8. return { count, decrement, increment }
  9. }
  10. let Counter = createContainer(useCounter)
  11. function CounterDisplay() {
  12. let counter = Counter.useContainer()
  13. return (
  14. <div>
  15. <button onClick={counter.decrement}>-</button>
  16. <span>{counter.count}</span>
  17. <button onClick={counter.increment}>+</button>
  18. </div>
  19. )
  20. }
  21. function App() {
  22. return (
  23. <Counter.Provider>
  24. <CounterDisplay />
  25. <Counter.Provider initialState={2}>
  26. <div>
  27. <div>
  28. <CounterDisplay />
  29. </div>
  30. </div>
  31. </Counter.Provider>
  32. </Counter.Provider>
  33. )
  34. }
  35. render(<App />, document.getElementById("root"))

参考文章