路由组件,
只有包裹在Route组件里的才能使用 this.props.location, this.props.history
<Route exact path="/Home" component={Home}/>
dva/withRouter
withRouter高阶组件,提供了history让你使用,
withRouter(App)组件后,App的 props会自动添加
- history
- location
- match

import {withRouter} from "react-router-dom";// dvaimport { withRouter } from 'dva/router'function List(props) {const urlObj = {pathname: `/detail/12`,state: {id: 1, user: 'lucy'}history.push(urlObj)console.log('func', props.history)// 不传参window.history.pushState(null, '', '/register')}export default withRoute(List)
withRouter错误
You should not use
withRouter 必须是 BrowserRouter包裹起来的路由
Uncaught Invariant Violation: You should not use <Route> or withRouter() outside a <Router>import { withRouter } from 'dva/router'function List() {return ()}withRouter(List)// 用Route包装 List组件<BrowserRouter basename='/'><Route path="/list" component={List}></Route></BrowserRouter>
detail组件接受 history参数
const { id, user } = this.props.location.state
ts-withRoute
interface PropsType {title: JSX.Element;sideImage: string;products: any[];}const ProductCollection: React.FC<PropsType> = ({title, sideImage, products}) => {return (<Link to={`detail/${id}`}>{size == "large" ? (<Image src={imageSrc} height={285} width={490} />) : (<Image src={imageSrc} height={120} width={240} />)}</Link>);}export const ProductImage = withRouter(ProductImageComponent);
class组件 withRoute
class List extends React.Component {myFunction() {this.props.history.push("/detail");}}export default withRouter(MyComponent);
useHistory
import { useHistory } from "react-router-dom";function HomeButton() {const history = useHistory();function handleClick() {history.push("/home");}return (<button type="button" onClick={handleClick}>Go home</button>);
