Taro+TypeScript - Mobx实践
# 学会使用mobx
# 一、建立store文件
import { observable } from 'mobx'
// 创建的是实例对象
const counter = observable({
counter: 0,
counterStore() {
this.counter++
},
increment() {
this.counter++
},
decrement() {
this.counter--
},
incrementAsync() {
setTimeout(() => {
this.counter++
}, 1000)
}
})
export default counter
# 二、引入store,并放入到provider中
import counter from './store/counter'
// 声明store
const store = {
counter
}
class App extends Component {render () {
return (
<Provider store={store}>
<Index />
</Provider>
)
}
}
# 三、在类中使用
import { observer, inject } from '@tarojs/mobx'
type propsType = {
price: {
price: number,
setPrice: Function
},
counter: {
counter: number,
increment: Function,
decrement: Function,
incrementAsync: Function
}
}
type stateType = {
}
interface Index {
props: propsType,
state: stateType
}
@inject('count', 'counter')
@observer
class Index extends Component {
constructor(props) {
super(props)
this.state = {
}
}
// mobx数据改变进行渲染函数()
componentWillReact () {}
increment = () => {
const { counter } = this.props
counter.increment()
}
decrement = () => {
const { counter } = this.props
counter.decrement()
}
incrementAsync = () => {
const { counter } = this.props
counter.incrementAsync()
}
render () {
const {counter: { counter }, price: { price } } = this.props
return (
<View className='index'>
<Button onClick={this.increment}>+</Button>
<Button onClick={this.decrement}>-</Button>
<Button onClick={this.incrementAsync}>Add Async</Button>
<Text>{counter}</Text>
</View>
)
}
}
# 参考
上次更新: 2021/12/19, 18:05:42