The first problem is right here:
render={(match) => ( ...
The render
function gets a props object which contains a match
property. Instead of destructuring the match
property, what you are actually doing is assigning the whole props
object to a variable match
. So when you go to access match.params
it won't be found.
You need curly braces around match
in order to destructure it.
render={({match}) => ( ...
The second problem is the nesting of the two Route
components. I get a warning:
Warning: You should not use <Route render>
and <Route children>
in the same route; <Route render>
will be ignored
So based on that warning you can see that your Redirect
is being entirely ignored since it comes from render
. The child Route
is seen as the render function for the classes Route
.
I'm assuming you have various subpages of a course? And we want to force the URL to include "/home" if none is set? (Personally I would do the opposite and redirect "/home" to the course root URL).
Previously I tried simply putting a Redirect tag with "from" and "to" but ran into the problem of the url actually going to "/classes/:course/home" instead of "/classes/BIO1001/home"
Per the docs, you can use params in your Redirect
, but only if it is inside a Switch
.
Here's a sample code to do that:
const CoursePage = () => {
// you can access arguments from the props or through hooks
const { course, tab } = useParams();
// not sure how you want to handle the different tabs
return <div>Viewing Course {course}</div>;
};
const App = () => (
<BrowserRouter>
<Switch>
<Route path="/classes/:course/:tab"><CoursePage/></Route>
<Redirect from="/classes/:course" to="/classes/:course/home"/>
</Switch>
</BrowserRouter>
);
export default App;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…