用于历史推送的 React Hooks 中等效的构造函数道具 [英] Constructor props equivalent in React Hooks for history push

查看:40
本文介绍了用于历史推送的 React Hooks 中等效的构造函数道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试迁移一个类组件以使用钩子运行,但是在尝试使用我的 history.push 更改 url 时遇到问题.

I'm trying to migrate one class component to function with hooks but i have a problem when try to change the url with my history.push.

对于我的类组件,这是更改 url 的方法:

With my class component this is the way to change the 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' }
})

并且工作正常,但在我的函数组件中,道具是空的,我不知道如何使用 history.push.

And works fine but in my function component the props its empty and i dont know how i cant use the history.push.

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

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

What i'm doing wrong? Thanks and sorry for the issues!

推荐答案

props.historyprops.location 是由注入的特殊 propswithRouter,适用于class功能组件

props.history and props.location are special props injected by withRouter, it works for class and functional 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)

这篇关于用于历史推送的 React Hooks 中等效的构造函数道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆