Mobx-React存储属性在第一次渲染时未定义,但异步加载变量通过



我正在使用Mobx管理我的状态。我为http请求调用一个操作来加载图片,然后更新图片属性,然后更新加载属性。当我加载进行调用的组件并console.log存储属性时,加载属性会更新,但picture属性仍然未定义。直到组件的第二次渲染,图片属性才被定义。下面是一个例子:

export class PhotoStore {
@observable picInfo = []
@observable loading = true
@action loadPics() {
this.loading = true;
let dataURL = 'some url';
return axios.get(dataURL)
.then(res => {this.picInfo = res.data})
.then(this.loading = false)
}
class PhotoGallery extends React.Component{
componentWillMount(){
this.PhotoStore.loadPics();
}
render(){
console.log(//these two properties)
//returns false and undefined object
return(
//some code
);
}
}

我知道我可以在渲染JSX之前检查picInfo.length,但我想让它发挥作用。感谢您提前提供任何提示!

您不需要第二个.then子句。当你设置this.picInfo时,也要设置this.loading。因为你把加载状态的改变放在了一个链式的promise中,所以在设置加载之前,@observable试图进行评估,这是一个时间问题。

https://mobx.js.org/best/actions.html-参见runInActionasyncAction装饰器

@action loadPics() {
this.loading = true;
let dataURL = 'some url';
return axios.get(dataURL)
.then(res => {runInAction(() => {this.picInfo = res.data})}
.then(runInAction(() =>this.loading = false))
}

最新更新