【问题标题】:With react-router-redux, how to programmatically redirect to a URL使用 react-router-redux,如何以编程方式重定向到 URL
【发布时间】:2025-12-02 18:50:02
【问题描述】:

如何以编程方式重定向到给定以下软件包的 URL:

"react-dom": "^15.5.4",
"react-redux": "^5.0.4",
"react-router-dom": "^4.1.1",
"react-router-redux": "^5.0.0-alpha.6",

我有这个工作:

import React from 'react';
import createBrowserHistory from 'history/createBrowserHistory';

class WorkPlacePage extends React.Component {
  render() {
    const history = createBrowserHistory();
    return (
      <div>
        <button onClick={() => history.push('/welcome/skills')}>next page</button>
      </div>
    );
  }
}

export default WorkPlacePage;

上述问题在于,当浏览器的 URL 发生变化时,React 应用程序似乎并未将 URL 更改视为重定向。应该由 URL 触发的 React 应用程序组件永远不会像 URL 被硬刷新时那样运行 React 组件逻辑。

如何以编程方式触发 React 应用加载新 URL 的 URL 重定向?

【问题讨论】:

    标签: reactjs redux react-router react-redux react-router-dom


    【解决方案1】:

    如果使用较新的 react-router API,您需要在组件内部使用 this.props 中的历史记录,因此:

    this.props.history.push('/some/path');
    

    但是,这可能仅用于以编程方式更改 URL,而不是实际导航到页面。你应该在你的路由器配置文件中有一些组件到这个 URL 的映射,就像这样。

    <BrowserRouter>
          <div>
            <Switch>
                <Route path="/some/path" component={SomeComponent} />
                <Route path="/" component={IndexComponent} />
            </Switch>
          </div>
    </BrowserRouter>
    

    希望这会有所帮助。快乐编码!

    【讨论】:

      最近更新 更多