【发布时间】: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 => console.error(error))。 -
您视图中的数据发生了变化?
-
是的,请看链接中的示例。您还应该写
.then(() => 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