【问题标题】:React-Router: Why does pushing to history change my url?React-Router:为什么推送到历史会改变我的网址?
【发布时间】:2018-09-24 21:45:09
【问题描述】:

我正在尝试利用 createMemoryHistory 在不更改 url 地址的情况下移动,因为我的应用程序将在 iframe 内呈现。但是,当我推送到history 时,它似乎更新了我的网址。任何提示将不胜感激!

//history.js
import createMemoryHistory from "history/createMemoryHistory";
const history = createMemoryHistory();
export default history;

//App.js
import history from './history/history';
...
<Router>
   <Route
      path={'/'}
      render={(props) => <Component {...props}/>}
   />
</Router>

//component.js
...
function handleClick(history) {
    history.push('somePath'); // this updates my url to be url.com/somePath
} 
return (<Button onClick={() => handleClick(this.props.history)}>);

【问题讨论】:

  • 你可以试试createBrowserHistory而不是MemoryHistory
  • @RaghavGarg 我刚刚换到createBrowserHistory,但它仍在更改我的网址:-(

标签: reactjs react-router history


【解决方案1】:

在使用MemoryHistory的时候,你应该把history对象传给Router,在导入创建的history之后直接使用

App.js

import history from './history/history';
...
<Router history={history}>
   <Route
      path={'/'}
      render={(props) => <Component {...props}/>}
   />
</Router>

component.js

import history from './history/history';
...
function handleClick() {
    history.push('somePath'); // this updates my url to be url.com/somePath
} 
return (<Button onClick={() => handleClick()}>);

【讨论】:

    【解决方案2】:

    解决了问题,我导入的东西不正确,哈哈。最后仍然坚持使用createMemoryHistory 而不是createBrowserHistory

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 2017-07-30
      • 2019-01-03
      • 2018-05-16
      • 2022-07-18
      相关资源
      最近更新 更多