React组件无法渲染求助:跟随教程时遇意外行为
Fixing Your React Component Rendering Issue
Hey Zac, let's break down why your components aren't rendering—there are a few syntax and setup issues in your code that are blocking this. Let's go through them one by one:
1. Invalid Route Syntax & Unclosed Tag
Your second <Route> has three clear problems:
- The path
'/store/:storei...'uses invalid syntax for URL parameters. If you're trying to define a dynamic parameter, it should be something clean like'/store/:storeId'(no trailing ellipsis). - The
<Route>tag isn't closed properly, which will throw a JSX syntax error right away. - You forgot to specify which component should render for this route (using the
componentprop, since you're using React Router v5 withSwitch).
2. Missing Render Call
You defined the root component, but you never told React to actually render it into the DOM. React needs a target DOM element (usually a <div id="root"> in your HTML) to mount your app to.
Here's the corrected version of your index.js code:
import React from 'react'; import { render } from 'react-dom'; import './css/style.css'; import App from './components/app'; import StorePicker from './components/storepicker'; import { Switch, Route } from 'react-router-dom'; // Capitalized component name (React convention for components) const Root = () => { return ( <Switch> <Route exact path='/' component={StorePicker} /> {/* Fixed path syntax, closed the tag, and added the component prop */} <Route path='/store/:storeId' component={App} /> </Switch> ); } // Mount the Root component to the DOM's root element render(<Root />, document.getElementById('root'));
Quick Extra Notes:
- I renamed
roottoRoot—it's a standard React convention to capitalize component names so React recognizes them as components instead of regular functions. - Double-check that your HTML file has a
<div id="root"></div>somewhere (usually inside the<body>) for React to attach your app to. - If you intended the
storei...to be a catch-all wildcard, React Router v5 uses*for that, likepath='/store/*'—but only use that if you need to match any subpath under/store/.
That should get your components rendering properly!
内容的提问来源于stack exchange,提问作者zac
相关产品推荐
相关产品推荐

