Reactjs 在React JS中以编程方式在子组件内部重定向不起作用

Reactjs 在React JS中以编程方式在子组件内部重定向不起作用,reactjs,routes,react-router,Reactjs,Routes,React Router,我正在使用React JS开发一个web应用程序。现在,我正试图通过编程重定向到另一个路由。我可以这样重定向 this.props.history.push('/event/${this.props.id}/edit'); 但当我在子组件中使用它时,它不起作用。这是我的设想。我有一个名为EventListComponent的父组件。在该组件中,我呈现另一个子组件EventWidgetComponent。我正在子组件中重定向。但是当我在子组件中使用this.props.history时,它总是未

我正在使用React JS开发一个web应用程序。现在,我正试图通过编程重定向到另一个路由。我可以这样重定向

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

但当我在子组件中使用它时,它不起作用。这是我的设想。我有一个名为EventListComponent的父组件。在该组件中,我呈现另一个子组件EventWidgetComponent。我正在子组件中重定向。但是当我在子组件中使用this.props.history时,它总是未定义的。如何修复它?

如果您想在子组件中使用它,可以将
历史记录
从您要提供的组件向下传递到
路由

示例

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>
    );
  }
}
类应用程序扩展了React.Component{
render(){
返回(
{/* ... */}
{/* ... */}
);
}
}
类父类扩展了React.Component{
render(){
返回(
);
}
}

发生这种情况是因为您的子组件没有访问历史记录的权限。子组件从父组件接收道具,而不是从路由器接收道具,这就是原因

以下是解决问题的可能方法:

1-将方法从父组件传递到子组件,并在父组件内执行重定向部分。从子组件调用该方法进行重定向

2-使用hoc并在其中呈现子组件,它将提供对子组件的历史访问

像这样:

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

// Child component here

class Child extends React.Component {
   // code
}

export default withRouter(Child)
检查以下答案:

3-通过道具将历史参考传递给孩子:

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

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

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

你是通过道具传递历史吗?非常感谢。充分的回答。干杯顺便说一句,它不会回家。但第二个选项会抛出此错误。对象作为React子对象无效(找到:具有键{pathname,search,hash,state}的对象)。如果要呈现子对象集合,请改用数组。该错误表示在代码中的某个位置呈现
历史对象
,该对象包含
路径名、搜索、状态等
,类似于:
{this.props.history}
。对象不是有效元素,请呈现特定值:)