在 Meteor 中更新集合后更新 DOM 中的值
Update value in DOM after updating collection in Meteor
我使用 react-toggle-button 插件在 React 中有一个切换按钮。
当您单击此按钮时,它会更新数据库中集合中的值。
问题是,除非您刷新页面,否则更新不会反映在 DOM 中。
有没有办法让数据立即更新值,以便切换实际上在视觉上切换?
这是按钮的代码:
<ToggleButton
value={d.showInClientMenu}
onToggle={value => {
Reports.update(
{ _id: d._id },
{ $set: { showInClientMenu: !value } }
);
value = !value
}}
/>
如果我单击此按钮并刷新页面,该按钮显示的值现在已不同,但除非立即反映出来,否则用户不会知道更改已经发生。
你必须像在集合 API 上那样尝试使用 Meteor Publish and subscribe
,如果集合是 lists
那么
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
export const Lists = new Mongo.Collection('lists');
if (Meteor.isServer) {
Meteor.publish('lists', function () {
return Lists.find({ userId: this.userId });
});
}
并在 imports/ui/ListsItem.js
import React from 'react';
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import { Links } from '../api/lists';
export default class ListsItem extends React.Component {
constructor(props) {
super(props);
this.state = {
lists: []
};
}
componentDidMount() {
this.listsTracker = Tracker.autorun(() => {
Meteor.subscribe('lists'); // Auto publish when loggedin
const lists = Lists.find({}).fetch();
this.setState({ lists });
});
}
componentWillUnmount() {
this.linksTracker.stop(); // Stop publish when logged out
}
render() {
return (
<div>
<p>Lists</p>
<div>
// Here is the view code and toggle
</div>
</div>
);
}
};
这只是 Publish and subscribe
实际工作方式的示例。
像这样实现后,数据会在创建或更改后立即自动显示。
另外,阅读这篇文章
我认为这会有所帮助。
我使用 react-toggle-button 插件在 React 中有一个切换按钮。
当您单击此按钮时,它会更新数据库中集合中的值。
问题是,除非您刷新页面,否则更新不会反映在 DOM 中。
有没有办法让数据立即更新值,以便切换实际上在视觉上切换?
这是按钮的代码:
<ToggleButton
value={d.showInClientMenu}
onToggle={value => {
Reports.update(
{ _id: d._id },
{ $set: { showInClientMenu: !value } }
);
value = !value
}}
/>
如果我单击此按钮并刷新页面,该按钮显示的值现在已不同,但除非立即反映出来,否则用户不会知道更改已经发生。
你必须像在集合 API 上那样尝试使用 Meteor Publish and subscribe
,如果集合是 lists
那么
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
export const Lists = new Mongo.Collection('lists');
if (Meteor.isServer) {
Meteor.publish('lists', function () {
return Lists.find({ userId: this.userId });
});
}
并在 imports/ui/ListsItem.js
import React from 'react';
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import { Links } from '../api/lists';
export default class ListsItem extends React.Component {
constructor(props) {
super(props);
this.state = {
lists: []
};
}
componentDidMount() {
this.listsTracker = Tracker.autorun(() => {
Meteor.subscribe('lists'); // Auto publish when loggedin
const lists = Lists.find({}).fetch();
this.setState({ lists });
});
}
componentWillUnmount() {
this.linksTracker.stop(); // Stop publish when logged out
}
render() {
return (
<div>
<p>Lists</p>
<div>
// Here is the view code and toggle
</div>
</div>
);
}
};
这只是 Publish and subscribe
实际工作方式的示例。
像这样实现后,数据会在创建或更改后立即自动显示。
另外,阅读这篇文章
我认为这会有所帮助。