import React from "react";
import { Router, Route, Switch, Redirect, HashRouter } from "react-router-dom";
import { createHashHistory } from "history";
...
const route = () => (
<HashRouter>
<Switch>
{/* 重定向不可放在首行 */}
{/* */}
<Route exact path="/" component={Home} />
<Route exact path="/listPage" component={ListPage} />
<Route exact path="/detailPage/:id" component={DetailPage} />
{/* 其他匹配重定向 */}
<Redirect path="*" to="/" />
</Switch>
</HashRouter>
);
export default route;
注意: 和 的区别 ==> 似乎没有区别
this.props.history.push('/listPage'): 路由入栈
this.props.history.replace('/listPage'):路由替换
this.props.history.goBack(): 返回上一级路由
http://localhost:3000/#/listPage
this.props.history.push({
pathname: '/listPage',
state: {
aaa: 123
},
});
// 跳转后新页面 通过 this.props.history.location.state 获取
// http://localhost:3000/#/listPage
·http://localhost:3000/#/listPage?bbb=456
this.props.history.push({
pathname: '/listPage',
search: '?bbb=456',
});
// 跳转后新页面 通过 this.props.history.location.search 获取
// url: http://localhost:3000/#/listPage?bbb=456
http://localhost:3000/#/detailPage/789
this.props.history.push({
pathname: '/detailPage' + '/' + id,
});
// 需要router.js 中路由配合:
// 跳转后新页面 通过this.props.match.params.id 获取
// url: http://localhost:3000/#/detailPage/789
import React from "react";
import { HashRouter, Route, Routes, Navigate } from "react-router-dom";
...
const route = () => (
<HashRouter>
<Routes>
<Route exact path="/" element={<Home />} />
<Route exact path="/listPage" element={<ListPage />} />
<Route exact path="/detailPage/:id" element={<DetailPage />} />
<Route exact path="*" element={<Navigate to="/" />} />
{/* } /> */}
</Routes>
</HashRouter>
);
export default route;
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
// push
navigate(path);
// replace
navigate(path, {replace: true});
const navigate = useNavigate();
// go back
navigate(-1);
http://localhost:3000/#/listPage
const navigate = useNavigate();
navigate('/listPage', {
state: {
aaa: '123',
}
})
// url: http://localhost:3000/#/listPage
http://localhost:3000/#/listPage?bbb=456
const navigate = useNavigate();
navigate('/listPage' + '?bbb=456')
// url: http://localhost:3000/#/listPage?bbb=456
http://localhost:3000/#/listPage/456
const navigate = useNavigate();
navigate('/detailPage' + '/' + id)
// 需要router.js 中路由配合: } />
// 跳转后新页面 通过 const { id } = useParams(); 获取,其中useParams 为 react-router-dom 内方法
// url: http://localhost:3000/#/detailPage/789
} />
} />