反应& mobx:渲染(通过方法render()) @observable数据,在渲染指定组件之后将进行修改

发布于 2025-01-24 12:22:41 字数 623 浏览 3 评论 0原文

请告知如何解决以下问题:

有一个组件输出一些计数器:

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

独行侠 2025-01-31 12:22:41

在MOBX中,您需要操纵动作中的观察者状态。

您应该扩展单身人士以看起来像这样:

export class MyData extends ISingleton
{
    @observable data: any = {}

    @action 
    setCounter(val: number) {
        this.data = val
    }
}

然后致电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:

export class MyData extends ISingleton
{
    @observable data: any = {}

    @action 
    setCounter(val: number) {
        this.data = val
    }
}

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

无妨# 2025-01-31 12:22:41

每个渲染都会创建一个全新的新数据对象,有效地将其重置。因此,您需要在类实例中存储数据,而不是在渲染中。此外,您正在修改的数据与您要渲染的数据完全不同(这就是new关键字的功能)。可能您想了解一些有关对象,类和amp;的信息。实例一般在JavaScript中工作

Every render creates a completely fresh new data object, effectively resetting it. So you want to store data 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 the new keyword does). Probably you want to read up a little on how objects, classes & instances work in JavaScript in general

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文