我有以下基本的 ReactJS
,但它不会改变路线。
Stackblitz:https://stackblitz.com/edit/react-testing-routes?file=src%2Fpages%2FPage1.jsx
演示:https://react-testing-routes.stackblitz.io/page3
这里有源代码:
App.js
import React from "react";
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Page1 from './pages/Page1';
import Page2 from './pages/Page2';
import Page3 from './pages/Page3';
import "./style.css";
export default function App() {
return (
<BrowserRouter>
<Switch>
<Route path="/" component={Page1 } />
<Route path="/page2" component={Page2 } />
<Route path="/page2" component={Page3 } />
</Switch>
</BrowserRouter>
);
}
Page1.jsx
import React from "react";
import { Link } from "react-router-dom";
class Page1 extends React.Component {
constructor(props) {
super(props);
this.state = {
letter: 'A',
};
}
render() {
return <>
<div>You are currently on: Page 1 (Letter: {this.state.letter})</div>
<Link to="/page2">Page 2</Link><br />
<Link to="/page3">Page 3</Link><br />
</>;
}
}
export default Page1;
Page2.jsx
// similar as Page1.jsx
Page3.jsx
// similar as Page1.jsx
package.json
{
"name": "react",
"version": "0.0.0",
"private": true,
"dependencies": {
"react": "17.0.0",
"react-dom": "17.0.0",
"react-router-dom": "^5.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"react-scripts": "latest"
}
}
知道如何改变路线吗?
谢谢!
答案 0 :(得分:2)
需要添加exact
prop,否则/page2
会被/
匹配:
<Switch>
<Route exact path="/" component={Page1} />
<Route exact path="/page2" component={Page2} />
<Route exact path="/page3" component={Page3} />
</Switch>
https://stackblitz.com/edit/react-testing-routes-ktkwg5?file=src.jsx
答案 1 :(得分:0)
使用exact
<BrowserRouter>
<Switch>
<Route exact path="/" component={Page1 } />
<Route path="/page2" component={Page2 } />
<Route path="/page2" component={Page3 } />
</Switch>
</BrowserRouter>