简体   繁体   中英

this.props.history.push() not working in ReactJS

Trying my hands at ReactJS fetch() examples. As mentioned this.props.history.push() not working, it is not giving an error, but it is simply not redirecting. Tried to read other answers to this question on StackOverflow, but many of them are either too complex(some ppl showing off) or some not very clear.

index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { BrowserRouter as Router, NavLink, Switch, Route, useHistory } from "react-router-dom";
import reportWebVitals from "./reportWebVitals";

ReactDOM.render(
    <React.StrictMode>
        <Router>
            <App />
        </Router>
    </React.StrictMode>,
    document.getElementById("root")
);

App.js:

import "./App.css";
import React from "react";
import { BrowserRouter as Router, NavLink, Switch, Route, useHistory } from "react-router-dom";
import RouterPage1 from "./RouterPage1";
import RouterPage2 from "./RouterPage2";

export default function App(props) {
    let history = useHistory();
    return (
        <div>
            <nav>
                <ol>
                    <li>
                        <NavLink to="/RouterPage1">RouterPage1</NavLink>
                    </li>
                    <li>
                        <NavLink to="/RouterPage2">RouterPage2</NavLink>
                    </li>
                    <li>
                        <NavLink to="/RouterPageBoth">RouterPageBoth</NavLink>
                    </li>
                </ol>
            </nav>
            <Switch>
                <Route exact path="/RouterPage1">
                    <RouterPage1 history={history} />
                </Route>
                <Route exact path="/RouterPage2">
                    <RouterPage2 history={history} />
                </Route>
            </Switch>
        </div>
    );
}

RouterPage2.js(only the necessary code pasted, not the entire component for brevity):

addastakeholder = () => {
    let newstakeholder = JSON.stringify(this.state.newstakeholder);

    fetch("http://localhost:8080/OneToOneMappingPractice/add", {
        method: "POST",
        headers: { "Content-type": "application/json" },
        body: newstakeholder,
    }).then((r) => {
        if (r.ok) {
            //window.location.href = "/RouterPage2";
            this.setState({ newstakeholder: { name: "", address: { house_number: "", streetName: "" } } });
            this.props.history.push("/RouterPage2");
        }
    });
};

when I use the addastakeholder(), it is POSTing successfully, data is being entered in the DB, but it is not giving me an error and not redirecting. In the App.js, if I use the props and not useHistory(), it gives me "this.props.history not defined" error, even though I have enclosed App component in BrowserRouter component in the index.js. Why is it so?

Secondly, if I use the commented out window.location.href = "/RouterPage2", it works(POSTing is successfull), but I am not able to see POST log in Development Tools:Network tab(Firefox). Why is this so?

Tried this.context.history.push("/RouterPage2"), does not work, same undefined error.

PS:edit 1:

the full RouterPage2.js(Kindly ignore result variable and the related code. Consider only result2.):

import React from "react";

export default class RouterPage2 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            stakeholders: [],
            errorString: "",
            newstakeholder: { name: "", address: { house_number: "", streetName: "" } },
        };
    }

    componentDidMount() {
        fetch("http://localhost:8080/OneToOneMappingPractice/getAll")
            .catch((error) => this.setState({ errorString: error }))
            .then((result) => result.json())
            .then((result) => this.setState({ stakeholders: result }));
    }

    addastakeholder = () => {
        let newstakeholder = JSON.stringify(this.state.newstakeholder);

        fetch("http://localhost:8080/OneToOneMappingPractice/add", {
            method: "POST",
            headers: { "Content-type": "application/json" },
            body: newstakeholder,
        }).then((r) => {
            if (r.ok) {
                //window.location.href = "/RouterPage2";
                this.setState({ newstakeholder: { name: "", address: { house_number: "", streetName: "" } } });
                this.props.history.push("/RouterPage2");
            }
        });
    };
    render() {
        let result, result2;
        let error = false;
        if (this.state.stakeholders.length > 0)
            result = (
                <ol>
                    {this.state.stakeholders.map((stakeholder) => (
                        <li key={stakeholder.stakeholder_id}>
                            {stakeholder.stakeholder_name} | {stakeholder.stakeholder_type} |
                            {stakeholder.stakeholder_email_id} | {stakeholder.stakeholder_contactno} |
                            {stakeholder.stakeholder_bankname} | {stakeholder.stakeholder_bankBranch} |
                            {stakeholder.stakeholder_IFSC} | {stakeholder.stakeholder_AccNo} |
                            {stakeholder.stakeholder_AccType} | {stakeholder.stakeholder_PAN}
                        </li>
                    ))}
                </ol>
            );
        else result = false;

        if (this.state.stakeholders.length > 0)
            result2 = (
                <ol>
                    {this.state.stakeholders.map((stakeholder) => (
                        <li key={stakeholder.id}>
                            {stakeholder.name}|{stakeholder.address.house_number}|{stakeholder.address.streetName}
                        </li>
                    ))}
                </ol>
            );
        else result2 = false;
        if (this.state.errorString !== "undefined") error = this.state.errorString;

        let blank = false;
        if (result == false) blank = <h5>There are no records to display.</h5>;
        return (
            <div>
                <h1>Stakeholder details :</h1>
                {result2}
                {error}
                {blank}
                <form>
                    Name :{" "}
                    <input
                        type="text"
                        placeholder="Name"
                        value={this.state.newstakeholder.name}
                        onChange={(e) => {
                            this.setState({ newstakeholder: { ...this.state.newstakeholder, name: e.target.value } });
                        }}
                    />
                    <br></br>
                    StreetName :{" "}
                    <input
                        type="text"
                        placeholder="StreetName"
                        value={this.state.newstakeholder.address.streetName}
                        onChange={(e) => {
                            this.setState({
                                newstakeholder: {
                                    ...this.state.newstakeholder,
                                    address: { ...this.state.newstakeholder.address, streetName: e.target.value },
                                },
                            });
                        }}
                    />
                    <br></br>
                    HouseNumber :{" "}
                    <input
                        type="text"
                        placeholder="HouseNumber(Digits Only)"
                        value={this.state.newstakeholder.address.house_number}
                        onChange={(e) => {
                            this.setState({
                                newstakeholder: {
                                    ...this.state.newstakeholder,
                                    address: { ...this.state.newstakeholder.address, house_number: e.target.value },
                                },
                            });
                        }}
                    />
                    <br></br>
                    <button type="button" onClick={this.addastakeholder}>
                        Add Stakeholder
                    </button>
                </form>
            </div>
        );
    }
}

Tried everything. As suggested by Kurtis above in the comments, for troubleshooting purposes, did: console.log(this.props);

Got following response:

在此处输入图像描述

as you can see, there is the push function with different signature, hence tried: this.props.history.push("/RouterPage2", ""). Again did not work.

Hence, thought of trying the go(). And it worked.

this.props.history.go("/RouterPage2"); working now perfectly.

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