路由组件,
只有包裹在Route组件里的才能使用 this.props.location, this.props.history

  1. <Route exact path="/Home" component={Home}/>

dva/withRouter

withRouter高阶组件,提供了history让你使用,
withRouter(App)组件后,App的 props会自动添加

  • history
  • location
  • match

image.png

  1. import {withRouter} from "react-router-dom";
  2. // dva
  3. import { withRouter } from 'dva/router'
  4. function List(props) {
  5. const urlObj = {
  6. pathname: `/detail/12`,
  7. state: {id: 1, user: 'lucy'}
  8. history.push(urlObj)
  9. console.log('func', props.history)
  10. // 不传参
  11. window.history.pushState(null, '', '/register')
  12. }
  13. export default withRoute(List)

withRouter错误

You should not use or withRouter() outside a
withRouter 必须是 BrowserRouter包裹起来的路由

  1. Uncaught Invariant Violation: You should not use <Route> or withRouter() outside a <Router>
  2. import { withRouter } from 'dva/router'
  3. function List() {
  4. return ()
  5. }
  6. withRouter(List)
  7. // 用Route包装 List组件
  8. <BrowserRouter basename='/'>
  9. <Route path="/list" component={List}></Route>
  10. </BrowserRouter>

detail组件接受 history参数

  1. const { id, user } = this.props.location.state

ts-withRoute

  1. interface PropsType {
  2. title: JSX.Element;
  3. sideImage: string;
  4. products: any[];
  5. }
  6. const ProductCollection: React.FC<PropsType> = ({title, sideImage, products}) => {
  7. return (
  8. <Link to={`detail/${id}`}>
  9. {size == "large" ? (
  10. <Image src={imageSrc} height={285} width={490} />
  11. ) : (
  12. <Image src={imageSrc} height={120} width={240} />
  13. )}
  14. </Link>
  15. );
  16. }
  17. export const ProductImage = withRouter(ProductImageComponent);

class组件 withRoute

  1. class List extends React.Component {
  2. myFunction() {
  3. this.props.history.push("/detail");
  4. }
  5. }
  6. export default withRouter(MyComponent);

useHistory

  1. import { useHistory } from "react-router-dom";
  2. function HomeButton() {
  3. const history = useHistory();
  4. function handleClick() {
  5. history.push("/home");
  6. }
  7. return (
  8. <button type="button" onClick={handleClick}>
  9. Go home
  10. </button>
  11. );