Reactjs,render() 在重定向后执行

Reactjs, render() is executed after redirect

componentDidMount() {
    if (sessionStorage.loggedInUser === undefined && localStorage.loggedInUser === undefined) {
        this.props.history.push("/");
    }
    //Check if user owns the car to see if we should send the ajax

    ajax.request.get("/cars/all").then((allCars) => {

        this.setState({
            allCars: allCars
        })
    })

}

componentWillMount() {
    if (sessionStorage.loggedInUser === undefined && localStorage.loggedInUser === undefined) {
        this.props.history.push("/");
    }
}

我有这个方法,我通过调试看到代码正在通过它们,但是在重定向之后它转到渲染方法并开始执行它。为什么?

我还没有测试过这个,但我认为你需要改用这个方法

this.history.replace("/")

一旦您开始安装组件,它的生命周期方法就会在队列中。在幕后,react 是 运行 这些方法生成的 "virtual dom"。即使结果永远无法完全到达用户,它们仍然需要出于 React 内部目的而执行。

不过从表面上看,您似乎想要一种中断 react-router 页面转换并将用户重定向到索引页面的方法。这绝对是可能的,但是 componentDidMount 挂钩不是它的正确位置。

你想要的是 onEnter 挂钩到 react router 的 Route 组件上,你可以用它来阻止或在安装过程开始之前重定向。

这在 V4 中被(愚蠢地)从 React 路由器中删除,并且社区......对此并不感到兴奋。你的用例是一个完美的例子,说明了为什么它是一个必要的钩子,以及为什么我建议坚持使用 react-router 的 V3,直到这个钩子被带回当前版本。