【问题标题】:Going to another page in ReactJS转到 ReactJS 中的另一个页面
【发布时间】:2020-01-18 17:05:38
【问题描述】:

我正在尝试学习 reactjs,我已经查找了很多不同的资源,从使用 react-route 到 react-route-dom,但是我尝试过的所有东西都不起作用,因为一切都说它起作用,所以我不确定我错过了什么。

我有一个名为 LoginForm 的类组件,它呈现表单并处理提交给 API 和处理响应的所有逻辑。

api 请求正在运行,并且我成功检查了登录是否有效,然后我想重定向到另一个名为 dashboard.html 的页面。

下面是我的组件类

import React from 'react'
import * as api from '../JSFuncs/APIManager'
import 'react-router-dom'

class LoginForm extends React.Component {

    constructor(props) {
        super(props);

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

        this.handleUsernameChange = this.handleUsernameChange.bind(this);
        this.handlePasswordChange = this.handlePasswordChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }


    handleUsernameChange(event) {
        this.state.username = event.target.value;
        this.setState(this.state);
    }

    handlePasswordChange(event) {
        this.state.password = event.target.value;
        this.setState(this.state);
    }


    handleSubmit(event) {

        event.preventDefault();

        this.props.history.push("dashboard.html");

        this.state.show_notice = true;

        this.setState(this.state);

        const postArray = {
            username: this.state.username,
            password: this.state.password
        };



        let comp = this;
        api.sendRequest(postArray, "admin/authenticator.php", "submitLogin").then(function(result){
            alert(JSON.stringify(result));

            if (result.result === 0)
            {
                if (result.data === 0) //Login OK
                {
                    comp.history.pushState(null, 'dashboard.html');
                    //comp.props.history.push('/dashboard.html');
                }
                comp.setState(comp.state);
            }
            else
            {
                comp.state.password = '';
                comp.state.error_msg = 'An error occurred with the DB';
                comp.setState(comp.state);
            }

            comp.state.show_notice = true;
            comp.setState(comp.state);
        })
    }
    render() {
        const style = this.state.show_notice === false ? {display: 'none'} : {};
        const { location, history } = this.props
        return (
            <section className="h-100">
                <div className="container h-100">
                    <div className="d-flex align-items-center justify-content-center h-100">
                        <div className="d-flex flex-column align-self-center">


                            <LoginStatus style={style} error_msg={this.state.error_msg} />

                            <form onSubmit={this.handleSubmit} className='form-horizontal align-self-center'>
                                <div className='form-group row'>
                                    <label htmlFor='txtUsername' className='col-sm-2 col-form-label'>Username: </label>
                                    <div className='col-sm-9'>
                                        <input type='text' className='form-control' id='txtUsername' value={this.state.username}
                                               placeholder='Your Username' onChange={this.handleUsernameChange}/>
                                    </div>
                                </div>
                                <div className='form-group row'>
                                    <label htmlFor='txtPassword' className='col-sm-2 col-form-label'>Password: </label>
                                    <div className='col-sm-9'>
                                        <input type='password' className='form-control' id='txtPassword' value={this.state.password}
                                               placeholder='Your password' onChange={this.handlePasswordChange}/>
                                    </div>
                                </div>
                                <div className='formButtonContainer'>
                                    <button className='btn-primary'>Login</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </section>
        );
    }
}

class LoginStatus extends React.Component
{


    render(){
        const className = this.props.error_msg === '' ? 'alert-info' : 'alert-warning';
        const msg = this.props.error_msg === '' ? 'You\'ve successfully logged in' : this.props.error_msg;
        return(
            <div style={this.props.style} className={'alert ' + className}>
                {msg}
            </div>
        )
    }
}

export default LoginForm

在handleSubmit 的响应中,我检查登录结果是否为0,然后我正在使用comp.history.pushState(comp 被声明为this,因此它在promise 的范围内)。

我已经尝试过 pushState 和 push 从其他示例中,但我得到了相同类型的错误。我也试过 comp.state.history.push 但没有运气。当我进行历史推送时,我成功登录并显示警报框,我得到以下信息:

TypeError: Cannot read property 'push' of undefined

如果这是一个简单的答案,我很抱歉,但我似乎无法从我用谷歌搜索的所有内容中了解它是如何工作的。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    在您的 App.js 中,您应该使用路由管理页面:

    import {BrowserRouter, Route, Switch} from "react-router-dom";
    import { createBrowserHistory } from "history";
    import {LoginForm} from './components/LoginForm';
    import {Dashboard} from './components/Dashboard';
    
    const history = createBrowserHistory();
    
    class App extends Component {
      constructor(props) {
        super(props);
        console.log(props)
      }
    
      render() {
    

    path="/" 是您的主页或主页 path="/dashboard" 是您的仪表板

    return (
      <BrowserRouter>
        <div>
          <Switch>
            <Route path="/" render={(props) => <LoginForm props={history} {...props} /> } exact />
            <Route path="/dashboard"  render={(props) => <Dashboard props={history} {...props} /> }/>
          </Switch>
        </div>
      </BrowserRouter>
    )
    

    然后在您的登录表单中,您可以

    export class LoginForm extends Component {
    
        constructor(props) {
            super(props);
            console.log(props)
        }
        go_dashboard = (e) => {
            this.props.history.push("/dashboard");
        }
    

    然后这将切换到您的仪表板组件。

    【讨论】:

    • 感谢 lehrm.ro。我仍然收到cannot read property of undefined。有什么东西应该放在你有props={...props} 的地方,因为它说它不喜欢......所以我试过没有,我也试过没有 props 参数,但我得到了相同的结果。跨度>
    • 感谢 lehrm.ro,在看到您的评论之前我设法修复了它,但我注意到我做了一些不同的事情。而不是props={history} {...props} 我刚刚放了{...props}。是有区别还是它们本质上是一样的
    • 您可以在此处阅读传播运算符:stackoverflow.com/a/42811937/12694208 很高兴它有帮助!如果它解决了您的问题,您会接受答案吗? :)
    • 感谢传播运算符的信息,非常方便。感谢您的帮助
    猜你喜欢
    • 2019-03-31
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 2021-03-11
    • 1970-01-01
    • 2013-05-16
    相关资源
    最近更新 更多