反应& mobx:渲染(通过方法render()) @observable数据,在渲染指定组件之后将进行修改
请告知如何解决以下问题:
有一个组件输出一些计数器:
@observer class MyComponent extends React.Component {
render() {
const data: MyData = new MyData();
return <div>{data['counter']}</div>;
}
}
计数器存储在可跟踪的(通过mobx @observable)singleton中:
export class MyData extends ISingleton
{
@observable data: any = {}
}
在某些时候,计数器(当已经创建了myComponent时),设置了计数器,
let data: MyData = new MyData();
data['counter'] = 123;
但是MyComponent并非重新绘制,尽管该组件似乎跟踪变量更改(通过mobx @observer和 @observable),
请告知错误在哪里以及如何修复它
Please advise how to solve the following problem:
There is a component that outputs some counter:
@observer class MyComponent extends React.Component {
render() {
const data: MyData = new MyData();
return <div>{data['counter']}</div>;
}
}
The counter is stored in a trackable (via mobx @observable) singleton:
export class MyData extends ISingleton
{
@observable data: any = {}
}
At some point the counter (when MyComponent is already created) the counter is set
let data: MyData = new MyData();
data['counter'] = 123;
But MyComponent is not redrawn, although the component seems to track variable change (via mobx @observer and @observable)
Please advise where is the error and how can it be fixed
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在MOBX中,您需要操纵动作中的观察者状态。
您应该扩展单身人士以看起来像这样:
然后致电SetCounter-hethod,而不是直接操纵状态。
请注意,从MOBX的第6版开始时,不建议使用Decorator API(请参阅更多信息)。
In mobx you need manipulate the state of observers within actions.
You should extend your singleton to look something like this:
Then call the setCounter-Method instead of manipulating the state directly.
Please take note that as of version 6 of MobX it is discouraged to use the decorator API (see this for more information).
每个渲染都会创建一个全新的新
数据
对象,有效地将其重置。因此,您需要在类实例中存储数据
,而不是在渲染中。此外,您正在修改的数据与您要渲染的数据完全不同(这就是new
关键字的功能)。可能您想了解一些有关对象,类和amp;的信息。实例一般在JavaScript中工作Every render creates a completely fresh new
data
object, effectively resetting it. So you want to storedata
at the class instance, not inside the render. Also the data you are modifying is completely different data than the data you are rendering (that is what thenew
keyword does). Probably you want to read up a little on how objects, classes & instances work in JavaScript in general