【问题标题】:Navigate with javascript using the MemoryRouter in react-router使用 react-router 中的 MemoryRouter 使用 javascript 导航
【发布时间】:2017-12-20 19:12:35
【问题描述】:

我正在使用 React 构建一个单页 Web 应用程序。对于这个应用程序,我想防止 URL 改变,也避免使用 href 链接来防止“链接预览”出现在浏览器的左下角。

为了解决我的问题的前半部分,我发现使用 react-router 中的 MemoryRouter 可以防止在应用程序中导航时更改 URL。

这是路由器的 PoC:

import App from './stuff/main/App';
import {Route, MemoryRouter} from "react-router";
import default_page from "./stuff/pages/default_page"
import another_page from "./stuff/pages/another_page"

const app = document.getElementById('root');
ReactDOM.render(
     <MemoryRouter>
       <App>
         <Route exact path="/" component={default_page} />
         <Route path="/anotherpage" component={another_page} />
       </App>
     </MemoryRouter>,
     app
);

然后在应用程序中我有这样的代码(有效):

...
<Link to="/">default_page</Link>
<Link to="/anotherpage">another_page</Link>
{this.props.children}
...

我不知道如何使用 MemoryRouter 在 javascript 中更改页面。我能找到的唯一可行的方法是使用 Link 标签,它会导致 url 显示在屏幕的左下角。如果我可以使用另一个元素并点击,我会很高兴。

【问题讨论】:

    标签: javascript html css reactjs react-router-v4


    【解决方案1】:

    如果你在&lt;Route&gt; 的子组件中,你应该有可用的历史道具:

    <button onClick={()=>this.props.history.push('/anotherpage')} >another_page</button>
    

    如果不是,你可以从父元素传递props.history

    或者如果你的结构很深,你应该使用withRouter HOC

    或者您可以创建一个不带 path 属性的新对象,这样它将始终匹配并为您提供正确的历史对象。

    <Route render={({history})=>(
      <button onClick={()=>history.push('/anotherpage')} >another_page</button>
      // more buttons
    )} />
    

    【讨论】:

    • 我正在尝试将 withRouter 用于深层嵌套组件,但出现错误:不变量失败:您不应该在 之外使用 你能指点我一个完整的吗工作示例?谢谢。我在这里发布了一个问题stackoverflow.com/questions/61031252/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 2021-07-16
    • 2020-05-18
    • 2022-01-01
    • 2021-04-24
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多