Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - Constructor props equivalent in React Hooks for history push

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.

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' }
})

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...