首页 > 解决方案 > 对象中的属性更新后,MobX 对象数组不会重新渲染

问题描述

此组件呈现一个包含 1 个值为“A”的单元格的表格。

单击“添加字符”按钮后,如何让我的表对 this.value[0].name 的值变化做出反应?

目前,当我单击“添加字符”按钮 2 次时,我可以通过 onClickAddCharacter() 中的 console.log 看到名称的值从“A”变为“ABB”。但是,正在呈现的表格并没有反映这个“ABB”新值,而是仍然是“A”。奇怪的是,如果我在 render() 中取消注释 console.log 并单击一次添加字符按钮,单元格值将从“A”重新渲染为“AB”。

这里发生了什么,我做错了什么?

谢谢!

编辑:我正在使用 MobX 5

import Button from 'main/component/Button';
import {action, observable} from 'mobx';
import {observer} from 'mobx-react';
import {Column} from 'primereact/column';
import {DataTable} from 'primereact/datatable';
import React from 'react';

@observer
class Component extends React.Component
{
    @observable
    private value = [{ name: 'A' }];

    @action.bound
    private onClickAddCharacter()
    {
        this.value[0].name += 'B';
        console.log(this.value);
    }

    render()
    {
        // If uncomment, the cell value will re-render from "A" to "AB"?
        // console.log(this.value);
        return (
            <>
                <DataTable value={this.value}>
                    <Column header='Name' field='name' />
                </DataTable>
                <Button title='Add character' onClick={this.onClickAddCharacter} />
            </>
        );
    }
}

标签: reactjsmobx

解决方案


因为您的DataTablefromprimereact本身不是观察者,所以您需要toJS在数据上使用 MobX 方法,然后再将其传递给DataTable.

import { toJS } from "mobx";

// ...

@observer
class Component extends React.Component
{
    @observable
    private value = [{ name: 'A' }];

    @action.bound
    private onClickAddCharacter()
    {
        this.value[0].name += 'B';
        console.log(this.value);
    }

    render()
    {
        return (
            <>
                <DataTable value={toJS(this.value)}>
                    <Column header='Name' field='name' />
                </DataTable>
                <Button title='Add character' onClick={this.onClickAddCharacter} />
            </>
        );
    }
}

推荐阅读