繁体   English   中英

如何获得Accounts.onLogin来影响我在Meteor React ES6中的应用?

[英]How to get Accounts.onLogin to impact my app in Meteor React ES6?

我希望流星应用程序在登录和注销时在App中调用setState。 如何让一段代码(即Accounts.onLogon)影响另一个组件(即App {})内部? 另外,如何检测注销?

Accounts.onLogin(function(user){
    console.log('hi');
    //App.showPrivate();
});

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      showPublic: false,
    };
  }

  toggleShowPublic() {
    this.setState({
      showPublic: !this.state.showPublic,
    });
  }

  showPublic() {
    this.setState({
      showPublic: true,
    });
  }

  showPrivate() {
    this.setState({
      showPublic: false,
    });
  }

  render() {
    return (
      <div className="container">
        <div className="show-public" onClick={this.toggleShowPublic.bind(this)}>
          {this.state.showPublic ?
            <span className="private-public"> View private</span> :
            <span className="private-public"> View public </span>
          }
        </div>
      </div>
    );
  }
}

而不是Accounts.onLogin您应该使用Meteor的内置反应性数据源来确定用户的登录状态:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { showPublic: false };
  }

  toggleShowPublic() {
    this.setState({ showPublic: !this.state.showPublic });
  }

  render() {
    return (
      <div className="container">
        {this.props.isLoggedIn ?
          <div className="show-public" onClick={this.toggleShowPublic.bind(this)}>
            {showPrivate ?
              <span className="private-public"> View private</span> :
              <span className="private-public"> View public </span>
            }
          </div> :
          Show something else if the user is not logged in here...
        }
      </div>
    );
  }
}

export default createContainer(() => {
  return {
    isLoggedIn: !!Meteor.user()
  }
}, App);

现在,Meteor将this.props.isLoggedIn为您动态更新this.props.isLoggedIn 请注意,您需要安装meteor/react-meteor-data并导入createContainer才能起作用:

import { createContainer } from 'meteor/react-meteor-data';

如果您在用户登录时仍需要执行某些操作,则可以将Accounts.onLogin基本上放置在应用程序中的任何位置,只要考虑要运行服务器端还是客户端,或者同时运行它们即可。 有关应用程序结构的最佳做法,请参阅《流星指南》

事实证明,Accounts.onLogin令人分心。 要在用户登录或注销时更新应用程序,我们需要查看登录用户的更改时间,并做出相应的反应。 使用componentWillReceiveProps来查看React中什么时候发生了变化,如下所示:

componentWillReceiveProps(nextProps) {
  // user just logged in/out
  if (!this.props.currentUser  &&  nextProps.currentUser) {
    this.setState({ showPublic: false });
  }
}

哦,当前用户来自:

export default createContainer(() => {
  return {
    currentUser: Meteor.user(),
  };
}, App);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM