React 路由器位置仅在某些组件中更新

React router location only updated in some components

无论是使用链接还是 this.props.history.push(),地址栏中的 URL 以及 DOM 树中更高层的组件中的 this.props.location 都正确更新(在这种情况下,我的 App 组件)。

但是,由于某种原因,它没有更新我的组件中的 this.props.location,这些组件位于树的更下方,这导致我的路由失败。

猜猜可能出了什么问题?

注意:我在这个项目中使用 redux,但我不会使用 redux 更改 this.props.history,至少现在是这样。我认为这不会影响任何事情,但如果有影响,请告诉我

编辑:如果有帮助,这里是 DOM 树的相关部分(我的电子邮件被小心地划掉了)。如您所见,Authenticated 组件有一个过时的 this.props.location (/plans),而 App 是正确的 (/posts)。两者都包裹在 withRouter 中。比 Authenticated 更靠下的组件也有错误的位置。

您可能正在处理 blocked updates。幸运的是,这并不难解决:

If you are running into this issue while using a higher-order component like connect (from react-redux), you can just wrap that component in a withRouter to remove the blocked updates.

// before
const MyConnectedComponent = connect(mapStateToProps)(MyComponent)
// after
const MyConnectedComponent = withRouter(connect(mapStateToProps)(MyComponent))

在我的例子中,这是 js 入口点的错误。我的代码是:

ReactDOM.render(
    <BrowserRouter>
        <App/>                       // <- missing Route!
    </BrowserRouter>,
    document.getElementById("app")
);

我通过添加 <Route/>:

修复了它
ReactDOM.render(
    <BrowserRouter>
        <Route component={App}/>
    </BrowserRouter>,
    document.getElementById("app")
);