我有一些代码,应该在最初加载或刷新屏幕时从API中重新加载数据。 当我使用mobx重新实现时,加载动画停止清除。 当我在两个方法中重写代码时,事情似乎可以工作,但我不想重复这样的代码。 我相信这与绑定有关。 下面是代码。
@observer
export default class Vehicles extends React.Component {
@observable client
@observable loaded = false
@observable refreshing = false
@action _loadScreen() {
this.client = global.store.currentUserStore.user
this.client.fetchVehicles().then(() => {
this.loaded = true
this.refreshing = false
})
}
@action _onRefresh = () => {
this.loaded = false
this.refreshing = true
this._loadScreen()
}
render() {
const { navigation } = this.props
this.navigation = navigation
return (
<SafeAreaView flex={1}>
<NavigationEvents
onDidFocus={() => Segment.screen("ScreenViewed")}
onWillFocus={() => this._loadScreen()}
/>
<Block flex>
<Loader loaded={this.loaded}/>
我试过用 @action.bound
和 runInAction
却无济于事。 我觉得我好像漏掉了什么小东西。 我对js也是相当陌生的(在我15年的职业生涯中,我只在这里和那里使用过一两行),所以请随时教育我任何我显然没有理解的概念。
谢谢!我有一些代码可以重新加载。
我相信问题出在你的 _loadScreen
方法。
尽管它被标记为 action
由于你使用的是一个承诺(异步),所以你的 then
方法的一部分是在初始动作之外运行的(_loadScreen
).
里面的代码是 then
也应在 action
.
import {runInAction} from 'mobx'
@action _loadScreen() {
this.client = global.store.currentUserStore.user
this.client.fetchVehicles().then(() => {
runInAction(()=>{
this.loaded = true
this.refreshing = false
})
})
}
来自文档。编写异步动作