React 变化
提示
需要注意的是,将您的前端代码迁移到异步是不必要的。您仍然可以在客户端使用同步 MongoDB 方法,例如:Collection.fetch
/Collection.findOne
。
但为了维护同构代码,您可以在客户端使用异步方法。
在这些情况下,我们实现了 suspense
版本的钩子,以便您可以使用异步方法。
例如
jsx
// you can write like this:
import { useTracker, useSubscribe } from 'meteor/react-meteor-data'
function Tasks() {
const isLoading = useSubscribe("tasks");
const { username } = useTracker(() => Meteor.user())
const tasksByUser = useTracker(() =>
TasksCollection.find({username}, { sort: { createdAt: -1 } }).fetch()
);
if (isLoading()) {
return <Loading />
}
// render the tasks
}
在 Meteor 3.x 中,您可以这样编写
jsx
import { useTracker, useSubscribe } from 'meteor/react-meteor-data/suspense'
function Tasks() { // this component will suspend
useSubscribe("tasks");
const { username } = useTracker("user", () => Meteor.userAsync())
const tasksByUser = useTracker("tasksByUser", () =>
TasksCollection.find({username}, { sort: { createdAt: -1 } }).fetchAsync()
);
// render the tasks
}
useFind
在客户端将保持不变。
您可以查看 react-meteor-data 文档 获取更多信息,以及这些博文 第一部分 第二部分 深入了解我们如何进行这些更改。