unstated状态管理库
安装
yarn add unstated
Github
官方链接:unstated
图示
代码
store
import { Container } from 'unstated';
// 全局
class Store extends Container {
constructor(initCount) {
super(...arguments);
this.state = {count: initCount || 0};
}
increment = () => {
this.setState({ count: this.state.count + 1 });
}
decrement = () => {
this.setState({ count: this.state.count - 1 });
}
}
export default Store
App
import React from 'react'
import { Provider } from 'unstated'
import Child1 from './Child1/index'
import Child2 from './Child2/index'
import Store from './store/index'
// 初始值
const counter = new Store(123)
class Parent extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
// 不注入的话,内部组件无法拿到默认值(123)去初始化数据
<Provider inject={[counter]}>
父组件
<Child1/>
<Child2/>
</Provider>
)
}
}
export default Parent
Child1
import React from 'react'
import { Subscribe } from 'unstated'
import Store from '../store/index'
class Child1 extends React.Component {
constructor(props) {
super(props);
}
render() {
return <Subscribe to={[Store]}>
{
counter => {
return <div>{counter.state.count}</div>
}
}
</Subscribe>
}
}
export default Child1
Child2
import React from 'react'
import { Subscribe } from 'unstated'
import Store from '../store/index'
class Child2 extends React.Component {
constructor(props) {
super(props);
}
render() {
return <Subscribe to={[Store]}>
{
counter => {
return <div>
<button onClick={counter.increment}>增加</button>
<button onClick={counter.decrement}>减少</button>
</div>
}
}
</Subscribe>
}
}
export default Child2
链接
引用地址