【问题标题】:Using history.push() while using a component within another component在另一个组件中使用一个组件时使用 history.push()
【发布时间】:2021-05-12 13:55:23
【问题描述】:

假设我有一个名为“Welcome.js”的组件,它是电子商务网站的欢迎页面。它呈现有关页面的一些信息,然后旁边有一个注册选项。注册部分,我已经编写为另一个组件,并从 Welcome.js 中调用它。传递正确的凭据后,注册页面应该重定向到仪表板。这适用于“Sign-up.js”的单个组件页面。但是当从欢迎页面完成同样的事情时,我收到以下错误:TypeError: Cannot read property 'push' of undefined

我是 React 新手,所以我的术语可能是错误的。我假设发生错误是因为我从另一个组件内的组件调用 history.push() 。有什么解决方法吗?

Welcome.js

import {Link} from 'react-router-dom';

class Welcome extends Component {

    constructor(props) {
        super();
        this.handleSubmit = this.handleSubmit.bind(this)
    }

    handleSubmit() {
        this.props.history.push('/SignUp')
    }

    render() {
        return (
            <div className="Welcome">
                <body>
                <nav>
                    <input type="checkbox" id="check"/>
                    <label htmlFor="check" className="checkBtn">
                        <i className="fas fa-bars"/>
                    </label>
                    <label className="logo">EStock</label>
                    <ul>
                        <li><Link to="/">Home</Link></li>
                        <li><Link to="/About">About</Link></li>
                        <li><Link to="/Contact">Contact</Link></li>
                        <li><Link to="/SignIn">Sign in</Link></li>
                        <li className="createAccountShort"><Link to="/SignUp">Create Account</Link></li>
                    </ul>
                </nav>
                <div className="content">
                    <h1>A New Way to Invest</h1>
                    <p>EStock is the best platform to help you analyse the latest stock trends
                        and decide the stock through which you can grow your wealth.</p>
                    <button onClick={this.handleSubmit} className="createAccount">Create Account ></button>
                </div>
                </body>
            </div>
        );
    }
}

export default Welcome

登录.js

import {Link} from "react-router-dom";

class SignIn extends Component {

    constructor(props) {
        super(props);
        this.state = {
            email: "",
            password: "",
            errorMessage: false
        }

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

    async handleSubmit(event) {
        event.preventDefault();
        event.stopPropagation();

        let response = await fetch('/customer/validateLogin', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': '*/*'
            },
            body: JSON.stringify({
                emailId: this.state.email,
                password: this.state.password
            })
        });
        let status = response.status;
        if (status === 200) {
            this.props.history.push({
                pathname: '/DashBoard',
                customer: await response.json()
            });
        } else if (status === 404) {
            this.setState({
                errorMessage: true
            })
        } else {
            this.props.history.push({
                pathname: '/Error404',
                message: 'Backend server is down'
            });
        }
    }

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

    validateForm() {
        return this.state.email.length > 0 && this.state.password.length > 0;
    }

    render() {
        return (
            <div>
                <div className="NAV">
                    <nav>
                        <input type="checkbox" id="check"/>
                        <label htmlFor="check" className="checkBtn">
                            <i className="fas fa-bars"/>
                        </label>
                        <label className="logo">EStock</label>
                        <ul>
                            <li><Link to="/">Welcome</Link></li>
                            <li><Link to="/About">About</Link></li>
                            <li><Link to="/Contact">Contact</Link></li>
                        </ul>
                    </nav>
                </div>
                <div className="SignUp">
                    <div className="register">
                        <h1>Enter your Credentials</h1>
                        <p>New at the portal?<Link to="/SignUp"> Sign Up</Link></p>
                    </div>
                    <div className="main">
                        <form onSubmit={this.handleSubmit}>
                            <h2 className="name">Email Address</h2>
                            <input
                                type="email"
                                name="email"
                                required="True"
                                className="email"
                                placeholder="Email address"
                                value={this.state.email}
                                onChange={this.handleChange}
                            />
                            <br/>
                            <h2 className="name">Password</h2>
                            <input
                                type="password"
                                name="password"
                                required="True"
                                className="password"
                                placeholder="Password"
                                value={this.state.password}
                                onChange={this.handleChange}
                            />
                            <h3 style={{display: this.state.errorMessage ? "block" : "none", color: "white"}}>Incorrect
                                Username/Password</h3>
                            <button className="registerButton" disabled={!this.validateForm}>Sign in</button>
                        </form>
                    </div>
                </div>
            </div>
        );
    }

}

export default SignIn```

import React, {Component} from "react";
import {Link} from "react-router-dom";

class SignIn extends Component {

    constructor(props) {
        super(props);
        this.state = {
            email: "",
            password: "",
            errorMessage: false
        }

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

    async handleSubmit(event) {
        event.preventDefault();
        event.stopPropagation();

        let response = await fetch('/customer/validateLogin', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': '*/*'
            },
            body: JSON.stringify({
                emailId: this.state.email,
                password: this.state.password
            })
        });
        let status = response.status;
        if (status === 200) {
            this.props.history.push({
                pathname: '/DashBoard',
                customer: await response.json()
            });
        } else if (status === 404) {
            this.setState({
                errorMessage: true
            })
        } else {
            this.props.history.push({
                pathname: '/Error404',
                message: 'Backend server is down'
            });
        }
    }

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

    validateForm() {
        return this.state.email.length > 0 && this.state.password.length > 0;
    }

    render() {
        return (
            <div>
                <div className="NAV">
                    <nav>
                        <input type="checkbox" id="check"/>
                        <label htmlFor="check" className="checkBtn">
                            <i className="fas fa-bars"/>
                        </label>
                        <label className="logo">EStock</label>
                        <ul>
                            <li><Link to="/">Welcome</Link></li>
                            <li><Link to="/About">About</Link></li>
                            <li><Link to="/Contact">Contact</Link></li>
                        </ul>
                    </nav>
                </div>
                <div className="SignUp">
                    <div className="register">
                        <h1>Enter your Credentials</h1>
                        <p>New at the portal?<Link to="/SignUp"> Sign Up</Link></p>
                    </div>
                    <div className="main">
                        <form onSubmit={this.handleSubmit}>
                            <h2 className="name">Email Address</h2>
                            <input
                                type="email"
                                name="email"
                                required="True"
                                className="email"
                                placeholder="Email address"
                                value={this.state.email}
                                onChange={this.handleChange}
                            />
                            <br/>
                            <h2 className="name">Password</h2>
                            <input
                                type="password"
                                name="password"
                                required="True"
                                className="password"
                                placeholder="Password"
                                value={this.state.password}
                                onChange={this.handleChange}
                            />
                            <h3 style={{display: this.state.errorMessage ? "block" : "none", color: "white"}}>Incorrect
                                Username/Password</h3>
                            <button className="registerButton" disabled={!this.validateForm}>Sign in</button>
                        </form>
                    </div>
                </div>
            </div>
        );
    }

}

export default SignIn

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    您的子组件没有路由道具。您需要将路由道具注入子组件。您可以通过将孩子包裹在 HOC 中并使用 withRouter 来做到这一点。

    【讨论】:

      【解决方案2】:

      您需要将 Welcome 组件包装在 withRouter HOC 中

      import { withRouter } from "react-router";
      
      ....
      
      export default withRouter(Welcome)
      

      https://reactrouter.com/web/api/withRouter

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-05
        • 1970-01-01
        • 2020-09-25
        • 2016-06-14
        • 1970-01-01
        • 2023-02-10
        相关资源
        最近更新 更多