如何在类组件中使用 useNavigate( ) React-Router-Dom Hook

Jay*_* jk 7 javascript reactjs react-router react-router-dom react-hooks

如何在类组件中使用 useNavigate( ) React-Router-Dom Hook ?

export default class MovieForm extends Form {
  state = {
    data : {},
    error : {},
  }
  onSubmit(){
    // Navigate to Another Component
  }
  render(){
  // rendering the Form UI
  }
}
Run Code Online (Sandbox Code Playgroud)

我想导航到提交表单时的另一个组件。

官方 React-Router-Dom 文档说我只能在功能组件内使用“useNavigate()”钩子。

我有一个类组件,但无法使其成为功能组件。因为它扩展了表单类,并且我想要此 MovieForm 组件中的表单类的所有功能。

那么我如何导航到另一个组件。

Dre*_*ese 6

如果你想使用useNavigate钩子,那么基本上有两种选择。

  1. 将基于类的组件转换为 React 函数组件并使用钩子useNavigate
  2. 创建一个自定义withRouter高阶组件,因为react-router-dom@6不再导出一个。

我不会介绍转换案例。这是一个withRouterHOC 实现。

例子:

import { useNavigate, /* other hooks */ } from 'react-router-dom'; 

const withRouter = WrappedComponent => props => {
  const navigate = useNavigate();
  // other hooks

  return (
    <WrappedComponent
      {...props}
      {...{ navigate, /* other hooks */ }}
    />
  );
};

export default withRouter;
Run Code Online (Sandbox Code Playgroud)

现在,您导入withRouter并装饰类组件,以便navigate任何其他 RRD 挂钩值都作为 props 注入。

...
import withRouter from '../path/to/withRouter';

class MovieForm extends React.Component { // *
  state = {
    data : {},
    error : {},
  }

  onSubmit() {
    const { navigate } = this.props;
    // Navigate to Another Component
    navigate("...target path...");
  }

  render() {
    // rendering the Form UI
  }
}

export default withRouter(MovieForm);
Run Code Online (Sandbox Code Playgroud)

* React 组件只能扩展React.Component,而不是其他自定义 Javascript 类!请参阅组合与继承


Meh*_*adi 3

从 React router v6 开始,您可以使用Navigate组件。

export default class MovieForm extends Form {
  state = {
    data : {},
    error : {},
    submitted : false,
  }
  onSubmit(){
    // Navigate to Another Component
    this.setState({submitted: true});
  }
  render(){
      // rendering the Form UI
      {submitted && 
        <Navigate to={// Router path to the target component} 
                  state={// you can pass state/props here}
        />
      }
  }
}
Run Code Online (Sandbox Code Playgroud)