【问题标题】:React Js renderings is functionalities not workingReact Js 渲染是功能不起作用
【发布时间】:2021-04-19 15:14:27
【问题描述】:

我是新来的反应。我很喜欢将用户名和密码编码到 js 页面中。我正在尝试将用户重定向到文本字段值的管理页面。这里提到了用户名和密码 Admin 然后我想将用户重定向到管理页面其他到主页但不工作。我还在 app.js 文件中定义了路由器。

这里是 app.js。

import React from 'react';
import { Router, Route, Switch, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';

import { history } from '../_helpers';
import { alertActions } from '../_actions';
import { PrivateRoute } from '../_components';
import { HomePage } from '../HomePage';
import { LoginPage } from '../LoginPage';
import { RegisterPage } from '../RegisterPage';
import CreateEmployeeComponent  from '../EmployeeComponets/CreateEmployeeComponent';
import ViewEmployeeComponent from '../EmployeeComponets/ViewEmployeeComponent';
import AdminComponent from '../EmployeeComponets/AdminComponent';


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

        history.listen((location, action) => {
            // clear alert on location change
            this.props.clearAlerts();
        });
    }

    render() {
        const { alert } = this.props;
        return (
            <div className="jumbotron">
                <div className="container">
                    <div className="col-sm-8 col-sm-offset-2">
                        {alert.message &&
                            <div className={`alert ${alert.type}`}>{alert.message}</div>
                        }
                        <Router history={history}>
                            <Switch>
                                <PrivateRoute exact path="/" component={HomePage} />
                                <Route path = "/add-employee/:id" component = {CreateEmployeeComponent} />
                               <Route path = "/view-employee/:id" component = {ViewEmployeeComponent} />
                          
                                <Route path="/login" component={LoginPage} />
                                <Route path="/register" component={RegisterPage} />
                                <Route path ="/admin" component={AdminComponent} />

                                <Redirect from="*" to="/" />
                            </Switch>
                        </Router>
                    </div>
                </div>
            </div>
        );
    }
}

function mapState(state) {
    const { alert } = state;
    return { alert };
}

const actionCreators = {
    clearAlerts: alertActions.clear
};

const connectedApp = connect(mapState, actionCreators)(App);
export { connectedApp as App };

这是 Login.js 的代码

import React from 'react';
import { Link, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';

import { userActions } from '../_actions';

class LoginPage extends React.Component {
    constructor(props) {
        super(props);

        // reset login status
        this.props.logout();

        this.state = {
            username: '',
            password: '',
            submitted: false
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(e) {
        const { name, value } = e.target;
        this.setState({ [name]: value });
    }

    handleSubmit(e) {
        e.preventDefault();

        this.setState({ submitted: true });
        const { username, password } = this.state;
        if (username && password) {
            this.props.login(username, password);
        }
        else if(username==="Admin" && password==="Admin"){
            localStorage.setItem("token" , "shjsshhbhbh")
            this.setState({
                loggingIn:true
              
            })

        }
    }

    render() {
        if(this.state.loggingIn){
            return <Redirect to ="/admin" />
        }
        const { loggingIn } = this.props;
        const { username, password, submitted } = this.state;
        return (
            <div className="col-md-6 col-md-offset-3">
                <h2>Login</h2>
                <form name="form" onSubmit={this.handleSubmit}>
                    <div className={'form-group' + (submitted && !username ? ' has-error' : '')}>
                        <label htmlFor="username">Username</label>
                        <input type="text" className="form-control" name="username" value={username} onChange={this.handleChange} />
                        {submitted && !username &&
                            <div className="help-block">Username is required</div>
                        }
                    </div>
                    <div className={'form-group' + (submitted && !password ? ' has-error' : '')}>
                        <label htmlFor="password">Password</label>
                        <input type="password" className="form-control" name="password" value={password} onChange={this.handleChange} />
                        {submitted && !password &&
                            <div className="help-block">Password is required</div>
                        }
                    </div>
                    <div className="form-group">
                        <button className="btn btn-primary">Login</button>
                        {loggingIn &&
                            
                        }
                        <Link to="/register" className="btn btn-link">Register</Link>
                    </div>
                </form>
            </div>
        );
    }
}

function mapState(state) {
    const { loggingIn } = state.authentication;
    return { loggingIn };
}

const actionCreators = {
    login: userActions.login,
    logout: userActions.logout
};

const connectedLoginPage = connect(mapState, actionCreators)(LoginPage);
export { connectedLoginPage as LoginPage };

这是私人路线代码

import React from 'react';
import { Route, Redirect } from 'react-router-dom';

export const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
        localStorage.getItem('user')
            ? <Component {...props} />
            : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
    )} />
)

这里是管理页面。

import React, { Component } from 'react'
import { Redirect } from 'react-router-dom';
import EmployeeService from '../services/EmployeeService';

class AdminComponent extends Component {
    constructor(props) {
        
        super(props)
        const token =localStorage.getItem("token")
        let loggedIn = true
        {
            if(token == null){
                loggedIn - false
            }
            this.state ={
                loggedIn
            }
        }

        this.state = {
            // step 2
            id: this.props.match.params.id,
            firstName: '',
            lastName: '',
            emailId: ''
        }
        this.changeFirstNameHandler = this.changeFirstNameHandler.bind(this);
        this.changeLastNameHandler = this.changeLastNameHandler.bind(this);
        this.saveOrUpdateEmployee = this.saveOrUpdateEmployee.bind(this);
    }

    // step 3
    componentDidMount(){

        // step 4
        if(this.state.id === '_add'){
            return
        }else{
            EmployeeService.getEmployeeById(this.state.id).then( (res) =>{
                let employee = res.data;
                this.setState({firstName: employee.firstName,
                    lastName: employee.lastName,
                    emailId : employee.emailId
                });
            });
        }        
    }
    saveOrUpdateEmployee = (e) => {
        e.preventDefault();
        let employee = {emailId: this.state.emailId,firstName: this.state.firstName, lastName: this.state.lastName};
        console.log('employee => ' + JSON.stringify(employee));

        // step 5
        if(this.state.id === '_add'){
            EmployeeService.createEmployee(employee).then(res =>{
                this.props.history.push('/employees');
            });
        }else{
            EmployeeService.updateEmployee(employee, this.state.id).then( res => {
                this.props.history.push('/employees');
            });
        }
    }
    
    changeFirstNameHandler= (event) => {
        this.setState({firstName: event.target.value});
    }

    changeLastNameHandler= (event) => {
        this.setState({lastName: event.target.value});
    }

    changeEmailHandler= (event) => {
        this.setState({emailId: event.target.value});
    }

    cancel(){
        this.props.history.push('/employees');
    }

    getTitle(){
        if(this.state.id === '_add'){
            return <h3 className="text-center">Add Employee</h3>
        }else{
            return <h3 className="text-center">Update Employee</h3>
        }
    }
    render() {
        if(this.state.loggedIn === false)
        {
            return <Redirect to ="/login" />
        }
        return (
            <div>
                <h1>Welcome to adimin </h1>
                <br></br>
                   <div className = "container">
                        <div className = "row">
                            <div className = "card col-md-6 offset-md-3 offset-md-3">
                                {
                                    this.getTitle()
                                }
                                <div className = "card-body">
                                    <form>
                                    <div className = "form-group">
                                            <label> Email Id: </label>
                                            <input placeholder="Email Address" name="emailId" className="form-control" 
                                                value={this.state.emailId} onChange={this.changeEmailHandler}/>
                                                </div>
                                        <div className = "form-group">
                                            <label> First Name: </label>
                                            <input placeholder="First Name" name="firstName" className="form-control" 
                                                value={this.state.firstName} onChange={this.changeFirstNameHandler}/>
                                        </div>
                                        <div className = "form-group">
                                            <label> Last Name: </label>
                                            <input placeholder="Last Name" name="lastName" className="form-control" 
                                                value={this.state.lastName} onChange={this.changeLastNameHandler}/>
                                        </div>
                                       
                                    

                                        <button className="btn btn-success" onClick={this.saveOrUpdateEmployee}>Save</button>
                                        <button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
                                        
                                         
             
                                    </form>
                                </div>
                            </div>
                        </div>

                   </div>
            </div>
        )
    }
}

export default AdminComponent

【问题讨论】:

  • 也请分享PrivateRoute
  • 添加私有路由

标签: javascript reactjs


【解决方案1】:

在您的handleSubmit 函数中,总是首先if 为真,然后javascript 没有检查另一个else if

您还需要添加另一个状态isAdmin 并像这样使用它:

const { username, password } = this.state;
if (username==="Admin" && password==="Admin") {
    this.props.login(username, password);
    localStorage.setItem("token" , "adminsaddad")
    this.setState({
        loggingIn:true,
        isAdmin:true
    })
} else if (username && password) {
    this.props.login(username, password);
    localStorage.setItem("token" , "shjsshhbhbh")
    this.setState({
        loggingIn:true
    })
}

然后检查用户是否是管理员:

if(this.state.loggingIn){
    if(this.state.isAdmin)
      return <Redirect to ="/admin" />
    else 
      return <Redirect to ="/" />
}

但这不是管理页面的安全方式,还应在您的 PrivateRoute 中添加管理组件并检查令牌然后重定向用户。

【讨论】:

  • 但问题是我传递给输入文件的用户名和密码将重定向到管理页面而不是主页
  • 立即查看答案!
  • 结果相同,但其他用户无法登录。我正在重用此链接中的代码。 jasonwatmore.com/post/2017/09/16/…
  • 它最初进入管理页面,但 3 秒后重定向到普通用户页面。我也添加了管理页面
  • 你的表单和 redux 操作有问题,你应该做一个代码框来帮助你。
猜你喜欢
  • 2016-02-07
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
  • 2021-08-23
  • 2021-01-19
  • 2020-09-17
  • 2018-09-21
相关资源
最近更新 更多