React Router Dom:如何将历史道具与其他道具一起使用

问题描述 投票:0回答:1

我正在将react-router-domreact一起使用。我正在尝试history prop

的其他道具
import React from 'react';

function MyComponent({ history }) {
   function redirect() {
      history.push('/path');
   }

   return (
      <>
         <button onClick={redirect}>Some Button</button>
      </>
   );
}

export default MyComponent;

这会起作用,但是如果我放另一个这样的道具

function MyComponent({myFunction, history}) {}

这不起作用

是否有其他替代方法,或者我做错了什么?

reactjs redirect react-router-dom history
1个回答
0
投票

相反,您可以使用useHistory()挂钩。

尝试以下操作:

import { useHistory } from 'react-router-dom';

function MyComponent({ myFunction }) {
   let history = useHistory();

   function redirect() {
      history.push('/path');
   }

   return (
      <>
         <button onClick={redirect}>Some Button</button>
      </>
   );
}

我希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.