在下面的基本示例中,我不清楚如何更新商店的实例(“” MyPanel.MyItems”),这样Mobx可以观察到值的变化,并有效地重新呈现MyList。
我正在跟踪示例,据我所知$r.MyItems.Items[4].OnlineStatus = 0/1
应该强制重绘。事实并非如此。
class MyItem {
id = 0;
onlineStatus = 0;
displayName = "";
thumbnail = "";
}
class MyStore {
constructor() {
this.items = [
{id:10, onlineStatus:0, displayName:'Bart', thumbnail: '' },
{id:20, onlineStatus:0, displayName:'Jean', thumbnail: '' },
{id:30, onlineStatus:1, displayName:'Emma', thumbnail: '' },
{id:40, onlineStatus:1, displayName:'Caitie', thumbnail: '' },
{id:50, onlineStatus:1, displayName:'Chris', thumbnail: '' },
];
}
}
@observer
class MyPanel extends React.Component{
@observable
MyItems = new MyStore();
Mylist = this.MyItems.items.map(MyItem => (
<li key={MyItem.id} onClick={this.toggleSelection.bind(this, MyItem.id)} >
<span>{MyItem.thumbnail}</span>{ MyItem.onlineStatus ? <i ></i> : <i ></i>} <p>{MyItem.displayName}</p>
</li>
));
render() {
return (
<div id="my-panel" >
<ul className="panel-list">
{this.Mylist}
</ul>
</div>
);
}
}
最佳答案
您需要确保从个人MyItem
到items
中的MyStore
的数据都是正确可观察的。
示例(JS Bin)
class MyItem {
@observable id = 0;
@observable onlineStatus = 0;
@observable displayName = "";
@observable thumbnail = "";
constructor(id, onlineStatus, displayName, thumbnail) {
this.id = id;
this.onlineStatus = onlineStatus;
this.displayName = displayName;
this.thumbnail = thumbnail;
}
}
class MyStore {
@observable items = [];
constructor() {
this.items.push(
new MyItem(10, 0, 'Bart', ''),
new MyItem(20, 0, 'Jean', ''),
new MyItem(30, 1, 'Emma', ''),
new MyItem(40, 1, 'Caitie', ''),
new MyItem(50, 1, 'Chris', '')
);
}
}
const myStore = new MyStore();
@observer
class MyPanel extends React.Component {
toggleSelection(item) {
item.onlineStatus = item.onlineStatus === 0 ? 1 : 0;
}
render() {
const myList = myStore.items.map(item => (
<li key={item.id} onClick={this.toggleSelection.bind(this, item)}>
<span>{item.thumbnail}</span>
{ item.onlineStatus ? <i>online</i> : <i >offline</i>}
<p>{item.displayName}</p>
</li>
));
return (
<div id="my-panel" >
<ul className="panel-list">
{myList}
</ul>
</div>
);
}
}
关于javascript - 如何更新值,以便Mobx导致渲染?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42726656/