我正在尝试迁移一个类组件来使用钩子,但是当我尝试用我的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")
}
我哪里做错了?对这些问题表示感谢和抱歉!
发布于 2019-09-26 17:54:11
props.history
和props.location
是withRouter
注入的特殊props
,它适用于class
和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)
发布于 2019-09-26 17:56:39
第一个:
import {withRouter} from "react-router-dom"
并包装您的组件
export default withRouter (PaisForm);
第二个:
或者,如果parent可以访问历史,则从parent传递历史对象,如下所示:
<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>
}
修复了打字错误
发布于 2019-09-26 18:14:45
您可以使用withRouter
高阶组件包装您的组件,该组件将提供history
作为支持:
import { withRouter } from 'react-router-dom';
const Component = ({ history, ...props }) => {
/* ... */
history.push('/');
}
withRouter(Component);
或者,您可以使用latest update (v5.1.0
)附带的钩子。有了这些,您就不必将您的功能组件包装在HOC中。
可用挂钩包括useHistory
(history
属性)、useLocation
(location
属性)、useParams
( match
属性的params
对象)和useRouteMatch
(match
属性)。
import { useHistory } from `react-router`;
const Component = (props) => {
const history = useHistory();
/* ... */
history.push('/');
}
https://stackoverflow.com/questions/58122219
复制