简体   繁体   English

this.props.history.push() 在 ReactJS 中不起作用

[英]this.props.history.push() not working in ReactJS

Trying my hands at ReactJS fetch() examples.在 ReactJS fetch() 示例中尝试我的手。 As mentioned this.props.history.push() not working, it is not giving an error, but it is simply not redirecting.如前所述 this.props.history.push() 不起作用,它没有给出错误,但它根本没有重定向。 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.试图在 StackOverflow 上阅读这个问题的其他答案,但其中很多要么太复杂(有些人炫耀)要么不太清楚。

index.js:索引.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:应用程序.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): RouterPage2.js(只粘贴了必要的代码,为简洁起见没有粘贴整个组件):

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.当我使用 addastakeholder() 时,它发布成功,数据正在输入数据库,但它没有给我一个错误,也没有重定向。 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.在 App.js 中,如果我使用 props 而不是 useHistory(),它会给我“this.props.history not defined”错误,即使我在 index.js 的 BrowserRouter 组件中包含了 App 组件。 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).其次,如果我使用注释掉的 window.location.href = "/RouterPage2",它可以工作(POST 成功),但我无法在开发工具:网络选项卡(Firefox)中看到 POST 日志。 Why is this so?为什么会这样?

Tried this.context.history.push("/RouterPage2"), does not work, same undefined error.尝试了 this.context.history.push("/RouterPage2"),不起作用,同样的未定义错误。

PS:edit 1: PS:编辑1:

the full RouterPage2.js(Kindly ignore result variable and the related code. Consider only result2.):完整的 RouterPage2.js(请忽略结果变量和相关代码。只考虑 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);正如 Kurtis 在上面的评论中所建议的那样,出于故障排除的目的,做了: 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", "").如您所见,存在具有不同签名的推送 function,因此尝试了:this.props.history.push("/RouterPage2", "")。 Again did not work.再次没有工作。

Hence, thought of trying the go().因此,想到尝试 go()。 And it worked.它奏效了。

this.props.history.go("/RouterPage2"); this.props.history.go("/RouterPage2"); working now perfectly.现在工作完美。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ReactJs this.props.history.push()不起作用 - ReactJs this.props.history.push() is not working this.props.history.push('/') 在 CLASS 组件中不起作用 - this.props.history.push('/') IS NOT WORKING in CLASS Component this.props.history.push刚刚刷新后正在运行 - this.props.history.push is working just after refresh React-router v4 this.props.history.push(...) 不工作 - React-router v4 this.props.history.push(...) not working this.props.history.push 在使用 HOC 记录器时不起作用 - this.props.history.push is not working while using HOC for logger ReactJS this.props.history.push不存在! this.props不包含历史记录 - ReactJS this.props.history.push doesn't exists! this.props doesn't include history 当我在同一路由中传递回调函数时 this.props.history.push() 不起作用 - this.props.history.push() is not working when i pass the callback function in same route 类型错误:无法使用 this.props.history.push 读取未定义的属性“推送” - TypeError: Cannot read property 'push' of undefined with this.props.history.push this.props.history.push 适用于某些组件而不适用于其他组件 - this.props.history.push works in some components and not others TypeError: undefined is not an object (评估 &#39;this.props.history.push&#39;) - TypeError: undefined is not an object (evaluating 'this.props.history.push')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM