前段时间用的redux,发现用起来非常麻烦,自己会用了也很难教会别人,昨天看了下mobx,用法如下 先定义一个类似于store的东西
import { observable } from 'mobx'
import { topicListApi } from '../config/api';
class topicStore {
@observable
topic = {
data: [],
page: 1,
tab: ''
}
constructor () {
this.getData()
}
getData = () => {
const { tab, page } = this.topic
topicListApi(page, tab).then((data: any) => {
if (data.success) {
this.topic = {
...this.topic,
data: data.data
}
}
})
}
filter = (tab: string) => {
this.topic.tab = tab
this.getData()
}
flip = (page: number) => {
this.topic.page = page
this.getData()
}
}
export default new topicStore();
然后在react组件内部
import {observer} from 'mobx-react';
import topicStore from '../../mobx/topic'
@observer
class TopicIndex extends React.Component<{}, any> {
render() {
...
{topicStore.topic.data.map((topic: topicObject, index: number) => {
return this.topicTemplate(topic, index)
})}
}
...
我就直接拿来用了,不像redux要绑定props,这样当store里的值发生变化,组件会自动刷,直接绕过react组件的state和props, 我想问下,这是正确用法吗?