【问题标题】:Mobx-React store property undefined on first render, but async loading variable passesMobx-React 存储属性在第一次渲染时未定义,但异步加载变量传递
【发布时间】:2017-10-17 10:59:44
【问题描述】:

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

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

【问题讨论】:

    标签: javascript reactjs mobx


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2023-01-14
        • 2021-11-22
        • 1970-01-01
        • 2021-11-10
        • 1970-01-01
        • 1970-01-01
        • 2019-07-25
        • 2022-10-08
        • 1970-01-01
        相关资源
        最近更新 更多