【问题标题】:React mobx update on API在 API 上反应 mobx 更新
【发布时间】:2019-01-01 16:00:00
【问题描述】:

mobx:5.03 反应:16.4.1 mobx 反应:5.2.3 导轨:5.0.2 反应轨宝石

我在 react 中有一个基本的 mobx 设置。我试图在 http 请求后让 rowData 可观察变量在视图中发生变化。但是,一旦它以默认的“111”呈现,它总是保持在该值。如何让 mobx 更新组件渲染?

import React from "react"
import axios from 'axios'

import { decorate, observable, computed, action } from "mobx"
import { observer } from "mobx-react"

class Device extends React.Component {
        rowData = 111 //view always stays at this value

        componentDidMount() {
            axios.get("/projects.json")
            .then(response => { this.rowData = 555 }) 
            .then(() => console.log(this.rowData)) //logs 555
        }

        render() {
            return (
                <div>
                    {this.rowData}
                </div> 
            );
        }

}

decorate(Device, {
    rowData: observable
})

export default observer(Device);

【问题讨论】:

  • It works for me。可能是您的 axios 请求失败。尝试在最后一个 then 之后添加 .catch(error =&gt; console.error(error))
  • 您视图中的数据发生了变化?
  • 是的,请看链接中的示例。您还应该写 .then(() =&gt; console.log(this.rowData))console.log(this.rowData) 将在您的请求之前运行,这不是您想要的。
  • 叹气,我将你的代码复制到我的应用程序中。。仍然呈现初始的 111 值。。我的堆栈上一定有东西。Rails/react-rails gem/webpack
  • 当您编写.then(console.log(this.rowData)) 时,您会立即调用console.log。如果您写.then(function () { console.log(this.rowData) }.bind(this)) 来查看差异,它可能看起来更清楚一些。我认为this is a great read on the subject.

标签: reactjs mobx mobx-react react-rails


【解决方案1】:

尝试用这个做一个构造函数:

constructor(props){
  super(props);
  makeObservable(this, {
    rowData: observable
  });
}

不确定这些功能在 5 中是否可用。可能需要升级 Mobx。

【讨论】:

    猜你喜欢
    • 2019-12-21
    • 1970-01-01
    • 2023-04-02
    • 2017-02-24
    • 2016-12-26
    • 2019-08-09
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    相关资源
    最近更新 更多