使用 react-router-redux,如何以编程方式重定向到 URL

With react-router-redux, how to programmatically redirect to a URL

如果有以下包,我如何以编程方式重定向到 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 应用程序组件永远不会 运行 React 组件逻辑,如果 URL 被硬刷新。

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

如果使用较新的 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>

希望这对您有所帮助。编码愉快!