demo 安装与运行
demo地址 react-unstated-next-demo
进入下载好的react-unstated-next-demo目录下
yarn install
yarn start
React轻量状态管理库 unstated-next 使用教程
1.安装
npm install --save unstated-next 或者 yarn add unstated-next
2.创建一个container
import { useState, useCallback } from "react"
import { createContainer } from "unstated-next"
function useCounter(initialState = 0) {
let [count, setCount] = useState(initialState)
let decrement = useCallback(() => setCount(count => count - 1), [])
let increment = useCallback(() => setCount(count => count + 1), [])
return { count, decrement, increment }
}
let CounterContainer = createContainer(useCounter)
export default CounterContainer
3.使用container
导入import CounterContainer from '../state/CounterContainer'
let counter = CounterContainer.useContainer()
import CounterContainer from '../state/CounterContainer'
export default function Counter() {
let counter = CounterContainer.useContainer()
console.log('Counter page render')
return (
<div>
<button onClick={counter.decrement}>-</button>
<span>{counter.count}</span>
<button onClick={counter.increment}>+</button>
</div>
)
}
4.使用Provider包裹
导入Container
import CounterContainer from '../state/CounterContainer'
<xxxx.Provider></xxxx.Provider>和initialState是固定写法
//初始化数据initialState,一定是这个变量名initialState
<CounterContainer.Provider initialState={10}>
<CounterPage />
</CounterContainer.Provider>
5.多层嵌套问题
当有多个Container Provider时,会有不断嵌套的问题
<Container1.Provider>
<Container2.Provider>
<Container3.Provider>
MyApp
</Container3.Provider>
</Container2.Provider>
</Container1.Provider>
6.解决方法
function compose(...containers) {
return function Component(props) {
return containers.reduceRight((children, Container) => {
return <Container.Provider>{children}</Container.Provider>
}, props.children)
}
}
let Provider = compose(Container1, Container2,Container1)
<Provider >
myApp
</Provider>