[英]Mobx-React store property undefined on first render, but async loading variable passes
我正在使用Mobx管理状态。 我为http请求调用一个操作来加载图片,然后更新pictures属性,然后更新loading属性。 当我加载使调用和console.log成为商店属性的组件时,加载属性会更新,但picture属性仍未定义。 直到组件的第二次渲染才定义了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。 因为您将加载状态更改放在了链式承诺中,所以存在一个时间问题,即@observable会在设置加载之前尝试评估。
https://mobx.js.org/best/actions.html-请参阅runInAction
和asyncAction
装饰器
@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))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.