我正在尝试个性化的navBar (路由器流量库)。特别是,当应用程序启动时,我将检查用户的角色,如果用户具有此角色,则在主页中这样做:"Role_Plus“他无法注销,因此文本”注销“不再出现,而在其他情况下则显示文本。
我在componentDidMount中创建了一个检查用户凭据的代码,它可以工作。但是在代码的呈现()部分中有一个错误,所以我不能使用。
当用户为Role_Plus时,我也尝试使用设置为1的标志,但此方法不起作用。
(我在出现错误的部分中注释了代码。)
这是代码:
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
flag: ''
};
this.flag = '';
}
componentDidMount() {
this.checkUser()
}
checkUser(){
User.getLoggedUser()
.then(dataUserLogged => {
if (dataUserLogged !== null) {
global.user = new User(JSON.parse(dataUserLogged));
// The console log print the right role without problems
console.log("User's Role: " + global.user.data.Roles)
if(global.user.data.Roles == "ROLE_PLUS") {
this.setState ({ flag: 1})
}
} })
.catch(err => {
console.log(err);
})
}
render() {
console.log("FLAG: " + this.state.flag)
return (
<Router>
<Scene key="root">
<Scene
key="homepage"
component={Homepage}
type="reset"
// I have tried this method but it doesn't work (The logout text is always display)
/*rightTitle={ this.state.flag === 1 ? "" : "Logout"}
onRight={
this.state.flag === 1
? () => {}
: () => Actions.refresh(App.logout())
}*/
// In this case there is an error: "Cannot read property 'data' of undefined "
rightTitle={ global.user.data.Roles !== "ROLE_PLUS" ? "Logout" : ""}
onRight={
globaluser.data.Roles !== "ROLE_PLUS"
? () => Actions.refresh(App.logout())
: () => {}
}
/>在您看来,如果角色不是:"logout",我如何检查凭据用户并显示文本"Role_Plus"?
非常感谢。
发布于 2019-08-07 08:39:50
'Global.user'是函数中的local variable,而'Global.user'的值在其他地方是未知的。请将该值传递给status值。
componentWillMount() {
this.checkUser()
}
checkUser(){
User.getLoggedUser()
.then(dataUserLogged => {
if (dataUserLogged !== null) {
global.user = new User(JSON.parse(dataUserLogged));
// The console log print the right role without problems
console.log("User's Role: " + global.user.data.Roles)
if(global.user.data.Roles == "ROLE_PLUS") {
this.setState ({ flag: global.user.data.Roles})
console.log("this is come in?");
}
} })
.catch(err => {
console.log(err);
})
}
...
rightTitle={ this.state.flag === "ROLE_PLUS" ? "Logout" : ""}发布于 2019-08-07 10:41:20
我以这种方式解决:
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
flag: 'ROLE_PLUS'
};
}
componentDidMount() {
this.checkUser()
}
checkUser(){
User.getLoggedUser()
.then(dataUserLogged => {
if (dataUserLogged !== null) {
global.user = new User(JSON.parse(dataUserLogged));
console.log("User's Role: " + global.user.data.Roles)
if(global.user.data.Roles != "ROLE_PLUS") {
this.setState ({ flag: ''})
}
} })
.catch(err => {
console.log(err);
})
}
render() {
console.log("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())
: () => {}
}
/>https://stackoverflow.com/questions/57389739
复制相似问题