【问题标题】:React Router: access history in rendered Route componentReact Router:渲染的 Route 组件中的访问历史记录
【发布时间】:2023-03-30 07:16:01
【问题描述】:

我知道对此有很多问题,但我似乎无法让它发挥作用:我需要从通过 Routes 呈现的子组件访问“历史记录”。 (它从一个 redux 容器接收 props)。

我需要将历史对象向下传递给每个 Route 中渲染的组件,以便我可以在子组件中this.props.history.push('/route')。此应用程序之前的动态性较低,因此每个 Route 都使用component={someComponent} 进行硬编码;但我发现在动态执行路由时,您需要使用render={() => <someComponent />}。

将路由从 component={} 更改为 render={() => ...} 后,我在子组件中丢失了历史记录。

我的代码是这样的:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import { HashRouter as Router, Link, Route, Redirect } from 'react-router-dom';

import { Nav_Item } from '.'
import DynamicTab from '.';

export default class NavBar extends React.Component {
  constructor(props) {
    super(props);
    this.state={}
  }
  render() {

    let tabs = [];

    let routes = [];

    this.props.tabs.forEach( function(tab, index) {
      tabs.push(<Nav_Item  key={tab.name} path_name={'/' + tab.name} tab_text={tab.label} />);
      routes.push(<Route key={tab.name} path={'/' + tab.name} render={() => <DynamicTab tabName={tab.name} tabSpecs={tab} />} />);
    })

    return (
      <Router>
        <div>

          <div>
            <ol>
              { tabs }    
            </ol>
          </div>

          <Redirect to={'/' + this.props.tabs[0].name} />
          { routes } 

        </div>
      </Router>   
    )
  }
}

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    当你使用render 时,你实际上得到了道具。在文档中,他们有一个这样的例子:

    <Route {...rest} render={props => (
       <FadeIn>
           <Component {...props}/>
       </FadeIn>
     )}/>
    

    所以您应该能够从这些道具访问历史记录。

    另一种解决方案是有条件地渲染&lt;Redirect/&gt; 组件。所以也许你有一些你像这样使用的内部状态:

    // in your components render function.. 
    if(this.state.shouldRedirect) { 
      return (<Redirect to={yourURL} />);
    }
    

    【讨论】:

    • 我避免渲染重定向,认为它太过分了。只需将道具作为路由渲染的参数就是我需要的解决方案。 render={ ({history}) =&gt; &lt;DynamicTab history={history} /&gt; } 是我的解决方案。感谢您的帮助!
    • 谢谢!这解决了我在使用 Context API 时在路由中使用渲染函数时丢失这些道具的问题
    【解决方案2】:

    this.props.router,您可以访问任何您想要的内容。

    在你的情况下,你可以这样做:

    this.props.router.push("/newurl");

    如果此组件由路由器渲染,则无需将历史记录作为单独的属性传递。

    【讨论】:

      猜你喜欢
      • 2016-08-21
      • 1970-01-01
      • 2019-05-09
      • 2019-08-03
      • 2023-03-08
      • 2020-02-25
      • 1970-01-01
      • 2017-08-01
      • 2021-03-21
      相关资源
      最近更新 更多