我有组件消耗上下文 api。每个列表项都有一个自定义链接以重定向到其页面。
我正在尝试渲染每个组件列表
对于“Product.jf,Details.js” 组件,我可以渲染它们。但是,对于“Cart.js”,我不能。
我需要你的帮助来解决这个问题。**
感谢您的帮助
{/* Section Component */}
import React, { Component } from "react";
import { Switch, Route } from "react-router-dom";
import Cart from "../Section/Cart";
import Details from "../Section/Details";
import Products from "../Section/Products";
export class Section extends Component {
render() {
return (
<section>
<Switch>
{/* <Route path="/" component={Products} exact /> */}
<Route path={"/product"} component={Products} exact />
<Route path={"/product/:id"} component={Details} exact />
<Route path={"/product/:id"} component={Details} exact />
<Route exact path={"/cart"} component={Cart} exact />
</Switch>
</section>
);
}
}
export default Section;
{/* App Component*/}
import React from "react";
import { BrowserRouter as Router } from "react-router-dom";
import AppFooter from "./components/layouts/AppFooter";
import AppNavbar from "./components/layouts/AppNavbar";
import { DataProvider } from "./components/layouts/Context";
import Section from "./components/layouts/Section";
function App() {
return (
<div>
<DataProvider>
<Router>
<AppNavbar />
<Section />
<AppFooter />
</Router>
</DataProvider>
</div>
);
}
export default App;
{/* Cart Component */}
import React, { Component } from "react";
import { DataContext } from "../layouts/Context";
export class Cart extends Component {
static contextType = DataContext;
render() {
const { cart } = this.context;
return (
<div>
<h1>Cart</h1>
</div>
);
}
}
export default Cart;
答案 0 :(得分:0)
your sandbox 中的第一个问题是,您不是在 App
内渲染 index.js
组件,而是其他内容。您还导入并使用了一个 Cart.js
文件,但其中没有任何内容。
Section
组件中的路由部分运行良好:
export class Section extends Component {
render() {
return (
<section>
<Switch>
<Route path="/product" component={Products} exact />
<Route path="/product/:id" component={Details} />
<Route path="/cart" component={Cart} />
</Switch>
</section>
);
}
}
index.js
ReactDOM.render(
<StrictMode>
<App />
</StrictMode>,
document.getElementById("container")
);
App.js
function App() {
return (
<div>
<DataProvider>
<Router>
<Section />
</Router>
</DataProvider>
</div>
);
}