检查用户凭证

时间:2019-08-08 10:42:23

标签: javascript react-native

我有一个问题。我不知道该如何解决这个问题。 基本上,在我的应用程序中,我有第一页App.js,其中定义了<Router><Scenes>(来自router-flux库)。

我的问题是我想检查用户的凭据,以更改用户角色的导航栏。特别是,如果用户具有ROLE_PLUS角色,则我不想在首页中显示注销文本(在导航栏中)。

但是我发现了一个问题,因为我可以轻松地恢复用户的角色,但是问题是首页上的导航栏是首先加载的。

此刻,我已经创建了一个角色,其角色为:ROLE_PLUS,如果登录用户的角色与此不同,则可以更改此标志。但是由于首先执行render(),因此无法正常工作。

您认为我该怎么办?非常感谢。

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      flag: 'ROLE_PLUS'
    };
  }

  componentDidMount() {
    this.checkUser()
    }
  checkUser(){
    User.getUserLogged()
        .then(dataUserLogged => {   
          if (dataUserLogged !== null) {
            global.user = new User(JSON.parse(dataUserLogged));
            console.log("1) User Role: " + global.user.data.Roles)
            if(global.user.data.Roles != "ROLE_PLUS") {
              this.setState ({ flag: ‘ROLE_NORMAL’})
              console.log("2) New Flag: " + this.state.flag)
            }
          } })
        .catch(err => {
          console.log(err);
        })
      }


  render() {
    console.log("3) FLAG: " + this.state.flag)    
    return (     
      <Router>
        <Scene key="root">
          //…
           <Scene
            key="homepage"
            component={Homepage}
            type="reset"
            rightTitle={ (this.state.flag != 'ROLE_PLUS')  ? "Logout" : ""}
            onRight={
              (this.state.flag != 'ROLE_PLUS' ) 
              ? () => Actions.refresh(App.logout())
              : () => {}
            }
            />

         //…

控制台命令打印为:(3)-(1)-(2)

1 个答案:

答案 0 :(得分:0)

您应该使用shouldComponentUpdate(nextProps,nextState)生命周期方法,而不要安装组件。在shouldComponentUpdate(nextProps,nextState)方法内,编写您的函数,最后返回true。

shouldComponentUpdate(nextProps, nextState) {
    this.checkUser();
    return true;
}

希望这会有所帮助。如果您想进一步了解React组件的生命周期方法,请阅读this

更新: 经过一段时间的寻找,我发现了另一个解决方法。您应该将checkUser定义为checkUser = functoin(){您的方法}。并从render()方法的开头调用该checkUser方法。让我知道此解决方法是否对您有用。

checkUser = function(){
User.getUserLogged()
    .then(dataUserLogged => {   
      if (dataUserLogged !== null) {
        global.user = new User(JSON.parse(dataUserLogged));
        console.log("1) User Role: " + global.user.data.Roles)
        if(global.user.data.Roles != "ROLE_PLUS") {
          this.setState ({ flag: ‘ROLE_NORMAL’})
          console.log("2) New Flag: " + this.state.flag)
        }
      } })
    .catch(err => {
      console.log(err);
    })
  }

    render() { 
        this.checkUser();
        .......your code......
   }
相关问题