首页 > 解决方案 > 如何使用 Meteor 和 React 一致地确定用户名

问题描述

我有一个简单的流星应用程序,其中包含一个显示用户名的组件:

const Welcome = ({ isLoading, username }) => {
  if (isLoading) {
    return <Loader />;
  } else {
    return <div>{username}</div>;
  }
};

我正在尝试通过传递用户名

const WelcomeContainer = withTracker(() => {
  const isLoading = !Meteor.user() || Meteor.loggingIn();
  const username = Meteor.user() ? Meteor.user().username : '';

  return {
    isLoading,
    username,
  };
})(Welcome);

如果我正常导航到组件,一切似乎都正常。但是,如果我刷新页面,大约有一半的时间会卡在加载组件上。(值得注意的是,我正在使用 ReactRouter)

更重要的是日志非常相似:

console.log(`client: ${Meteor.isClient} and isLoading: ${isLoading}`);

// Username displayed successfully
client: true and isLoading: true (x2)
client: true and isLoading: true (x2)
client: true and isLoading: false (x2)

// Stuck on Loading
client: true and isLoading: true (x2)
client: true and isLoading: false (x2)

我误解了跟踪器吗?我需要在这里订阅一些东西吗?如何让组件始终显示用户名?

标签: meteormeteor-accounts

解决方案


问题是我有<React.StrictMode>。删除它可以解决问题。


推荐阅读