5

给定以下软件包,我如何以编程方式重定向到 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 重定向?

4

1 回答 1

3

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

希望这可以帮助。快乐编码!

于 2017-05-31T03:22:15.507 回答