【问题标题】:Programmatically redirecting inside child component in React JS is not working在 React JS 中以编程方式重定向子组件内部不起作用
【发布时间】:2018-12-19 20:14:11
【问题描述】:

我正在使用 React JS 开发一个 Web 应用程序。现在,我正在尝试以编程方式重定向到另一条路线。我可以这样重定向。

this.props.history.push('/event/${this.props.id}/edit');

但是当我在子组件中使用它时它不起作用。这是我的场景。我有一个名为 EventListComponent 的父组件。在该组件中,我渲染了另一个名为 EventWidgetComponent 的子组件。我在子组件中重定向。但是当我在子组件中使用 this.props.history 时,它总是未定义。我该如何解决?

【问题讨论】:

  • 你是通过 props 传递history 吗?

标签: reactjs routes react-router


【解决方案1】:

发生这种情况是因为您的子组件无权访问历史记录。子组件接收来自父组件而不是来自Router 的道具,这就是原因。

这些是解决问题的可能方法:

1- 要么将方法从父级传递给子级,然后在父组件内执行重定向部分。从子组件调用该方法进行重定向。

2- 使用withRouter hoc 并在其中渲染子组件,它将提供对子组件的历史访问。

像这样:

import { withRouter } from 'react-router-dom'

// Child component here

class Child extends React.Component {
   // code
}

export default withRouter(Child)

查看这个答案:Programmatically navigating in React-Router v4

3-将历史的引用传递给props中的child:

<Child history={this.props.history} />

【讨论】:

  • 非常感谢。足够的答案。干杯。顺便提一句。它没有回家。
  • 但是第二个选项会抛出这个错误。对象作为 React 子对象无效(找到:带有键 {pathname, search, hash, state} 的对象)。如果您打算渲染一组子项,请改用数组。
  • 该错误意味着您正在渲染 history object 的代码中的某处,其中包含 pathname, search, state etc,类似于:&lt;div&gt;{this.props.history}&lt;/div&gt;。对象不是有效元素,渲染具体值 :)
【解决方案2】:

您可以将 prop 传递给从父 EventListComponent 传递的 EventWidgetComponent,例如 onHistoryPush:

<EventWidgetComponent onHistoryPush={() => this.props.history.push('/event/${this.props.id}/edit')}

【讨论】:

    【解决方案3】:

    如果你想在那里使用它,你可以将 history 属性从你提供给 Route 的组件传递给子组件。

    示例

    class App extends React.Component {
      render() {
        return (
          <div>
            {/* ... */}
            <Route exact path="/" component={Parent} />
            {/* ... */}
          </div>
        );
      }
    }
    
    class Parent extends React.Component {
      render() {
        return (
          <div>
            <Child history={this.props.history} />
          </div>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多