简体   繁体   中英

How to add roles in ReactJS?

I want to add roles to admin when login so admin can create new user. I dont know how to add the roles and make it works. Here's my code:

Login.js

 class Login extends Component { constructor(props) { super(props); this.state = { username: "", password: "", } } onChangeInput = e => { this.setState({ [e.target.name]: e.target.value }) } onLogin = async () => { const { username, password } = this.state const exist = this.props.listUsers.find(user => user.username === username) if (exist) { this.props.changeLogIn() } else if(username === 'admin' && password === "123") { const roles = "ADMIN"; this.props.changeLogIn() } } render() { if (this.props.statusLogin){ return <Redirect to="/about" /> } return ( <div className="login"> <form className="login-form" method="POST"> <div className="container-log"> <h1 className="judul">Login</h1> <RowInput value={this.state.username} label="Username" placeholder="Username" type="text" name="username" onChange={this.onChangeInput}/> <RowInput value={this.state.password} label="Password" placeholder="Password" type="password" name="password" onChange={this.onChangeInput}/> <Button onClickInput={this.onLogin}>Masuk</Button> </div> </form> </div> ); } }

Body.js

 showPage = () => { const { changeLogIn, statusLogin } = this.props return ( <Switch> <Route path="/about" children={(props) => <About {...props} statusLogin={statusLogin} listUsers={this.state.userData} />} /> <Route path="/login"> <Login changeLogIn={changeLogIn} listUsers={this.state.userData} statusLogin={statusLogin} /> </Route> <Route path="/register"> <Register listUsers={this.state.userData} tambahUser={this.addUsers} /> </Route> </Switch> ) }

App.js

 class App extends Component { constructor(props) { super(props); this.state = { page: "login", isLoggedIn: false } } changeLogIn = () => { this.setState(oldState => ({ isLoggedIn: !oldState.isLoggedIn })) }

Yes, I know this code wouldn't work (esp Login.js), but again, I dont know how to fix it. Like, somewhat I have the solutions on my head, but I can't code it. Thank you before!

Admin , user roles is something that we should do it in the backend but if you are trying to do it in front end then , There should be one super admin (he an add new admins or user ) , admins (he can add users)

store the login details in cookie or localstorage , and redirect the user if he is not authorized , I can code if you ask me something specific

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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