繁体   English   中英

React:我如何(动态地?)从数据生成页面?

[英]React: how can I (dynamically?) generate pages from Data?

在我的应用程序中,我有:

A StockData.JS file with 50 different Stocks
--> A StockTile Component, that is populated with Data from the StockData file
 ---> A StockDetailPage Component also populated with Data from the StockData file

在此处输入图片说明

StockTile 和 StockDetail Page 这两个组件都完全填充了数据。 将它们映射到概览页面可提供获得 50 个 Tile 组件的预期结果,每个组件都填充了单独的数据。

因为所有这 50 个磁贴应该导致 50 个单独的详细信息页面,也填充了数据:

我怎样才能让 React 自动/动态生成 50 个不同的 StockDetailPages(据说每个页面都有一个单独的链接?)*到目前为止我已经了解了使用 React 的映射、过滤和道具,但我对如何生成完全一无所知动态页面。

您需要使用 react-router 包:(已完成的示例代码沙箱

 //package.json "react-router": "5.2.0", "react-router-dom": "5.2.0",

并创造历史

 import createHistory from "history/createBrowserHistory"; const history = createHistory(); export default history;

定义路由

 import React, { useState } from "react"; import { Router, Switch, Route, useParams } from "react-router"; import { Link } from "react-router-dom"; import createHistory from "history/createBrowserHistory"; import ProjectSingle from "./ProjectSingle"; import "./styles.css"; const history = createHistory(); const Footer = () => { return <div > Footer here. < /div>; }; export default function App() { const [projects, setProjects] = useState([{ title: "Stock One", image: "/img/wp-logo.png", slug: "stock-one", key: 1 }, { title: "Stock Two", image: "/img/wp-logo.png", slug: "stock-two", key: 2 } ]); /*const getProjects = () => { fetch('http://localhost:8000/projects') .then((res) =>{ return res.json(); }) .then((data) => { setProjects(data); }) } useEffect(() => { getProjects(); AOS.init({disable: 'mobile'}); },[]); */ return ( < Router history = { history } > < div className = "App" > { projects.map((project) => { return ( < div key = { project.key } > < Link to = { `/project/${project.slug}` } > { project.title } < /Link> < /div> ); }) } < Switch > { projects.map((project) => ( < Route key = { project.key } exact path = "/project/:slug" render = { (props) => < ProjectSingle { ...props } project = { project } />} / > )) } < /Switch> < Footer / > < /div> < /Router> ); }

定义详细信息组件

 import React from "react"; import { Router, Switch, Route, useParams } from "react-router"; const ProjectSingle = ({ project }) => { const { slug } = useParams(); //TODO useEffect to get project details return ( < > < h1 > Details of { slug } < /h1> < div > { JSON.stringify(project) } < /div> < /> ); }; export default ProjectSingle;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM