最近在写react的项目,发现React-router4.x和React-router3.x差别挺大的,以下是我项目中实现react路由跳转的两种方法。
安装React-router
在React-router4中,react-router-dom和history是必不可少的。
- npm install --S react-router
- npm install --S react-router-dom
- npm install --S history
配置index.js入口文件
不管是哪一种方法,都不能缺少在index.js入口文件配置路由匹配规则。
1、react-router V4版本丢弃IndexRoute,用exact和Switch替代。
React-router官方文档是使用了IndexRoute(默认路由),但是在v4版本中如果引入IndexRoute是会报错的,因为它被丢弃了,被exact替代了。
exact表示只对当前的路由进行匹配,Switch组件表示独立路由。如果不使用exact和Switch时,会同时渲染’/‘和’/admin’组件,比如这样。
因此需要将 ‘/admin’ 路由放在 ‘/’ 之前,因为后者包含了前者,但是一旦进入到’/admin’页面,也会渲染’/’。如果使用了exact(不使用Switch)就可以不用关注顺序了。
2、<Router history={history}>
的实现效果和<BrowserRouter>
一样。<BrowserRouter>
和<HashRouter>
的区别是:HashRouter有#
import { Router, Route, BrowserRouter, HashRouter,Switch,Redirect } from "react-router-dom";
import { createBrowserHistory } from "history";
import App from "./pages/MainPageLayout/App";
import Login from "./pages/login/Login";
const history = createBrowserHistory();
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Switch>
<Route exact path="/" component={Login}></Route>
<Route path="/admin" component={App}></Route>
//重定向
<Redirect to="/" />
</Switch>
</Router>
</Provider>,
document.getElementById("root")
);
第一种(推荐)
这种是官网的写法,当继承组件之后,this.props.history.push("/admin");
就可以实现页面的跳转
class Login extends Component {
constructor(props) {
super(props);
};
onFinish = values => {
this.props.history.push("/admin");
};
render() {
return (
<div>
<div className="loginCenter">
<Form
{...this.layout}
name="basic"
onFinish={this.onFinish}
>
<Form.Item {...this.tailLayout}>
<Button type="primary" htmlType="submit">
登录
</Button>
</Form.Item>
</Form>
</div>
</div>
);
}
}
export default withRouter(Login);
第二种
当Login是函数时,如果单单只有history.push("/admin");
时,会出现路由发生变化但是页面没有渲染的情况,必须得加上history.go();
才会渲染页面。所以我觉得这种方法不太好
const Login = () => {
const onFinish = values => {
history.push("/admin");
history.go();
};
return (
<Form
{...this.layout}
onFinish={this.onFinish}
>
<Form.Item {...this.tailLayout}>
<Button type="primary" htmlType="submit">
登录
</Button>
</Form.Item>
</Form>
);
};
export default withRouter(Login);
PS:如果对我的代码和react项目感兴趣,欢迎clone我的react项目https://github.com/faimi/my-react