reactjs - 对象中的属性更新后,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} />
</>
);
}
}
解决方案
因为您的DataTable
fromprimereact
本身不是观察者,所以您需要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} />
</>
);
}
}
推荐阅读
- eventbrite - Eventbrite - 使用 REST API 发布事件
- python - 处理 Unicode 字符
- javascript - 嵌套 for 循环的迭代问题
- c - openssl api 函数参考问题
- vba - 在工作簿/工作表打开时创建持久 ADODB 连接
- python - 如何生成具有预定义概率分布的随机数?
- salesforce - 如何在 Salesforce 中重命名我的 Apex 类名称
- c++ - 使用 GetNetworkParams() 检索网络信息时出错
- php - 知道一个加密字符会导致安全漏洞吗?
- jenkins - Groovy FTP 上传后存档文件损坏