React Hooks中用于替代构造函数props的history push的相应方法是什么?

9
我将尝试将一个类组件迁移到使用hooks的函数中,但是当我尝试使用history.push更改URL时遇到了问题。
使用类组件时,更改URL的方法如下:
  constructor(props) {

    super(props)

    this.state = {
     // GeneralValidate: false,
      paisValue: '',
      paisError: true,
      loading: false,
      tipo: '',
  };

  }


.//more code here


 this.props.history.push({
  pathname: '/Pais',
  state: { detail: 'hola' }
})

这段代码在普通组件中可以正常工作,但在我的函数组件中,props为空,我不知道如何使用history.push方法。

 const PaisForm = (props) => { 
 props.history.push("/Pais")
}

我做错了什么?谢谢并对问题感到抱歉!

你是否在一个函数式组件中使用了 withRouter 高阶组件? - Dupocas
使用withRouter连接或从父组件传递history对象 - Jaisa Ram
3个回答

11

props.historyprops.location是由withRouter注入的特殊props,适用于classfunctional components

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

export const Component = withRouter(({ history, location }) =>{

})

class Comp extends Component {
    render(){
        const { location, history } = this.props
    }
}
export default withRouter(Comp)

4

第一:

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

并将你的组件包装起来

export default withRouter (PaisForm);

第二种方法:

如果父级组件可以访问history对象,也可以将其从父级组件传递下来,如下所示:

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

第三步:

使用路由器中的 useHistory hooks。

import { useHistory } from 'react-router';

function PaisForm (props){
  const history = useHistory();

  return <button onClick={()=> history.push('/path')}>click</button>
}

修改错别字


React-Router-Dom V6 怎么样?它不再支持 withRouter。 - Aman Ullah

1

您可以使用withRouter高阶组件来包装您的组件,它将提供history作为属性:

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

const Component = ({ history, ...props }) => {

    /* ... */

    history.push('/');

}

withRouter(Component);

或者您可以使用附带的钩子v5.1.0最新更新)。使用这些钩子,您不必将功能组件包装在HOC内。

可用的钩子有useHistoryhistory属性),useLocationlocation属性),useParamsmatch属性的params对象)和useRouteMatchmatch属性)。

import { useHistory } from `react-router`;

const Component = (props) => {
    const history = useHistory();

    /* ... */

    history.push('/');
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接