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

时间:2017-10-17 02:42:12

标签: javascript reactjs mobx

我正在使用Mobx管理我的州。我为一个http请求调用一个动作来加载图片,然后更新pictures属性,然后更新加载属性。当我加载进行调用的组件和console.log存储属性时,loading属性会更新,但是图片属性仍未定义。直到第二次渲染组件才定义了图片属性这是一个例子:

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,但我想让它工作。提前感谢任何提示!

2 个答案:

答案 0 :(得分:0)

您不需要第二个.then子句。设置this.picInfo时,也设置this.loading。因为您将加载状态更改放在链式承诺中,所以有一个计时问题,@ observable在设置加载之前尝试进行评估。

答案 1 :(得分:0)

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))
}