第一步先建立一个类似redux中reducer的文件
runInAction可以解决获取异步数据问题
import { observable, action, runInAction } from 'mobx'
class List {
// 树叶变成响应数据
@observable listData: Array<any> = []
// @computed计算属性
// MobX 配置为需要通过动作来更改状态时,必须使用 action,做一些事件
@action
getCateData () {
fetch('https://ik9hkddr.qcloud.la/mock/cookbook-list.json')
.then(reponse => reponse.json())
.then(result => {
runInAction(() => {
this.listData = result.data
})
})
}
}
export default new List()
第二步在 利用mobx-react将mobx和react粘合,并在componentDidMount钩子中触发获取数据的函数action
import React from 'react'
import { Provider } from 'mobx-react'
import Home from './pages/home/Home'
import store from './store'
export default class componentName extends React.Component {
render() {
return (
<Provider store={store}>
<Home></Home>
</Provider>
)
}
componentDidMount () {
store.list.getCateData()
}
}
import { observer, inject } from 'mobx-react'
interface Props {
store?: any
}
interface State {
hotCateList: Array<any>
list: Array<any>
}
//inject将store注入组件
@inject('store')
// @observer吧数据变成响应式
@observer
export default class componentName extends Component<Props, State> {
}
第四步 直接在树枝上获取数据,在render中渲染
render() {
const listData = this.props.store.list.listData
return ()}