Misalkan saya memiliki komponen bernama "Welcome.js" yang merupakan halaman selamat datang untuk situs web e-niaga. Itu membuat beberapa informasi tentang halaman dan kemudian memiliki opsi pendaftaran di sampingnya. Bagian pendaftaran, saya telah menulis sebagai komponen lain dan menyebutnya dari Welcome.js. Ketika kredensial yang benar diteruskan, halaman pendaftaran seharusnya dialihkan ke dasbor. Ini berfungsi baik dengan halaman komponen individual "Sign-up.js". Tetapi ketika hal yang sama dilakukan dari halaman selamat datang, saya mendapatkan kesalahan berikut:TypeError: Cannot read property 'push' of undefined

Saya baru mengenal Bereaksi sehingga terminologi saya mungkin salah. Saya berasumsi kesalahan terjadi karena saya memanggil history.Push() dari komponen yang ada di dalam komponen lain. Apakah ada solusi untuk ini?

Selamat datang.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

Masuk.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

enter image description here

enter image description here

0
Ankita Paul 12 Mei 2021, 16:55

2 jawaban

Jawaban Terbaik

Komponen anak Anda tidak memiliki props perutean. Anda perlu menyuntikkan alat peraga perutean ke komponen anak. Anda dapat melakukannya dengan membungkus anak dalam HOC dan menggunakan withRouter.

1
Sam Vruggink 12 Mei 2021, 14:13

Anda perlu membungkus komponen Selamat Datang Anda di withRouter HOC

import { withRouter } from "react-router";

....

export default withRouter(Welcome)

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

0
AJ72 12 Mei 2021, 14:13