【问题标题】:Constructor props equivalent in React Hooks for history push用于历史推送的 React Hooks 中等效的构造函数道具
【发布时间】:2019-09-26 17:50:38
【问题描述】:

我正在尝试迁移一个类组件以使用钩子功能,但是在尝试使用我的 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' }
})

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

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

我做错了什么?感谢和抱歉的问题!

【问题讨论】:

  • 您是否将功能组件包装在 withRouter hoc 中?
  • 与 withRouter 连接或从父级传递历史对象

标签: javascript reactjs


【解决方案1】:

props.historyprops.locationwithRouter注入的特殊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)

【讨论】:

    【解决方案2】:

    第一个:

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

    并包装你的组件

    export default withRouter (PaisForm);
    

    第二个:

    如果父级有权访问历史记录,则从父级传递历史记录对象,如下所示:

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

    第三:

    使用来自路由器的useHistory 钩子

    import { useHistory } from 'react-router';
    
    function PaisForm (props){
      const history = useHistory();
    
      return <button onClick={()=> history.push('/path')}>click</button>
    }
    

    修正错别字

    【讨论】:

    • react-router-dom v6 怎么样?它不再支持 withRouter
    【解决方案3】:

    您可以使用 withRouter Higher-Order-Component 包装您的组件,这将提供 history 作为道具:

    import { withRouter } from 'react-router-dom';
    
    const Component = ({ history, ...props }) => {
    
        /* ... */
    
        history.push('/');
    
    }
    
    withRouter(Component);
    

    或者您可以使用latest update (v5.1.0) 附带的挂钩。有了这些,您不必将功能组件包装在 HOC 中。

    可用的钩子是useHistory (history prop)、useLocation (location prop)、useParams (params object of match prop) 和 useRouteMatch (match prop) .

    import { useHistory } from `react-router`;
    
    const Component = (props) => {
        const history = useHistory();
    
        /* ... */
    
        history.push('/');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-03
      • 2020-08-15
      • 2021-11-11
      • 2019-02-06
      • 2021-09-06
      • 2019-07-07
      相关资源
      最近更新 更多