React 路由器 - 单击卡片并使用 useParams 和 reacthooks 重定向到包含该卡片内容(卡片详细信息)的新页面 [英] React router - click on card and redirect to a new page with content of that card (card details) using useParams and reacthooks

查看:51
本文介绍了React 路由器 - 单击卡片并使用 useParams 和 reacthooks 重定向到包含该卡片内容(卡片详细信息)的新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一篇博文.帖子位于卡片 [Event.js] 中,点击按钮即可.它应该转到新页面并在那里呈现其卡片详细信息.我如何使用 react hooks 和 useParams 来做到这一点?EventList.js --->是我从 api 获取数据的地方Event.js --->我在卡片中呈现获取的数据EventDetails.js --->单击帖子时,应在屏幕上呈现卡片详细信息.现在我已经硬编码了.详情.

有人可以帮我解决这个问题吗?

//EventList.js

import React, { useState, useEffect } from "react";从../Event/Event"导入事件;从axios"导入 axios;从./EventList.module.css"导入样式;const EventList = () =>{const [posts, setPosts] = useState("");让 config = { 授权:………………";};const url = ……………………";;useEffect(() => {所有帖子();}, []);const AllPosts = () =>{公理.get(`${url}`, { headers: config }).then((响应) => {const allPosts = response.data.articles;控制台日志(响应);setPosts(allPosts);}).catch((error) => console.error(`Error: ${error}`));};返回 (<div><Event className={styles.Posts} posts={posts}/>

);};导出默认事件列表;

//Event.js

从反应"导入反应;从./Event.module.css"导入样式;从react-router-dom"导入{链接};导入bootstrap/dist/css/bootstrap.min.css";const 事件 = (道具) =>{const displayPosts = (props) =>{const { 帖子} = 道具;如果 (posts.length > 0) {返回posts.map((post) => {返回 (<div><div><div className={styles.post}>

);});}};return <div className="Posts">{displayPosts(props)}</div>;};导出默认事件;

//EventDetails.js

import React, { useState, useEffect } from "react";从../Navbar/Navbar"导入导航栏;从../../assets/Event-Ticketing.png"导入DetailsImage;从./EventDetails.module.css"导入样式;导入bootstrap/dist/css/bootstrap.min.css";import { Link, useParams, useLocation } from react-router-dom";从axios"导入 axios;//let config = { 授权:3055f8f90fa44bbe8bda05385a20690a"};//const baseurl = "https://newsapi.org/v2/top-headlines?sources=bbc-news";const EventDetails = (props) =>{const { state } = useLocation();if (!state) 返回空值;//const [title, setTitle] = useState("");//const { eventName } = useParams();//useEffect(() => {//轴//.get(`${baseurl}`, { headers: config })//.then((response) => setTitle(response.data));//}, []);//useEffect(() => {//const neweventName = baseurl.find(//(eventNames) =>eventNames.eventName === parseInt(eventName)//);//setTitle(neweventName.title);//}, []);返回 (<div><导航栏/><div className={styles.eventBg}><div className="容器"><div>

<div className={styles.bookingDetails}><div className={styles.nameBook}><div><div className={styles.eventNameHeader}><h1 className={styles.eventName}>{props.title}

<div className={styles.genre}><div className={styles.genreText}>{props.author}</div>

<div className={styles.bookingBtn}><div className={styles.booking}><链接到=/GeneralBooking"><按钮className={styles.bookBtn}style={{ height: "60px", fontSize: "18px";}}>书</链接>

<div className={styles.venueTime}><div className={styles.dateTime}><div className={styles.dateTimeText}>{props.author}</div><div className={styles.price}>{props.author}</div>

);};导出默认的 EventDetails;

//App.js

import "./App.css";从react-router-dom"导入 { BrowserRouter, Route, Switch };从./components/Home/Home"导入主页;从./components/EventDetails/EventDetails"导入事件细节;从./components/GeneralBooking/GeneralBooking"导入GeneralBooking;从./components/AllotedSeated/AllotedSeated"导入 AllotedSeated;从./components/Checkout/Checkout"导入结帐;功能应用(){返回 (<浏览器路由器>

<开关><路由路径="/";精确><首页/></路线><路由路径=/:title";确切的孩子={<EventDetails/>}></Route><Route path="/GeneralBooking";精确><一般预订/></路线></开关>{/* <事件详细信息/>*/}{/* <GeneralBooking/>*/}{/* <AllotedSeated/>*/}{/* <结帐/>*/}

</BrowserRouter>);}导出默认应用程序;

解决方案

因为它看起来好像你已经将 posts 状态存储在 ReactTree 中足够高以供组件访问在其他路由上,我建议使用路由状态将特定的 post 对象发送到接收路由.

事件 - 更新 Link 以同时发送 post 对象.

<链接到={{路径名:`/${post.title}`,状态:{发布},}}><按钮类型=按钮";className={styles.btns}>{post.author}</button></链接>

EventDetails - 使用 useLocation 钩子访问路由状态.

import { useLocation } from react-router-dom";const EventDetails = (props) =>{const { state } = useLocation();if (!state.post) 返回空值;返回 (//...渲染 state.post 中可用的所有 post 字段//即 state.post.title);};

I have created a blog post. Posts are in the card[Event.js] and on click of the button. It should go to the new page and render its card details there. How can I do it using the react hooks and useParams.? EventList.js ---> is where I'm fetching the data from api Event.js ---> I'm rendering the fetched data in cards EventDetails.js ---> It's the card details that should render on the screen when clicked on the post. Right now I have hard coded. the details.

Could someone please help me with how to do this?

//EventList.js

import React, { useState, useEffect } from "react";
import Event from "../Event/Event";
import axios from "axios";
import styles from "./EventList.module.css";

const EventList = () => {
  const [posts, setPosts] = useState("");

  let config = { Authorization: "..........................." };
  const url = "............................................";

  useEffect(() => {
    AllPosts();
  }, []);

  const AllPosts = () => {
    axios
      .get(`${url}`, { headers: config })

      .then((response) => {
        const allPosts = response.data.articles;
        console.log(response);
        setPosts(allPosts);
      })
      .catch((error) => console.error(`Error: ${error}`));
  };

  return (
    <div>
      <Event className={styles.Posts} posts={posts} />
    </div>
  );
};

export default EventList;

//Event.js

import React from "react";
import styles from "./Event.module.css";
import { Link } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";

const Event = (props) => {
  const displayPosts = (props) => {
    const { posts } = props;

    if (posts.length > 0) {
      return posts.map((post) => {
        return (
          <div>
            <div>
              <div className={styles.post}>
                <img
                  src={post.urlToImage}
                  alt="covid"
                  width="100%"
                  className={styles.img}
                />
                <div>
                  <h3 className={styles.title}>{post.title}</h3>
                  <div className={styles.price}> {post.author} </div>
                  <Link to={`/${post.title}`}>
                    <button className={styles.btns}> {post.author} </button>
                  </Link>
                </div>
              </div>
            </div>
          </div>
        );
      });
    }
  };
  return <div className="Posts">{displayPosts(props)}</div>;
};

export default Event;

//EventDetails.js

import React, { useState, useEffect } from "react";
import Navbar from "../Navbar/Navbar";
import DetailsImage from "../../assets/Event-Ticketing.png";
import styles from "./EventDetails.module.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { Link, useParams, useLocation } from "react-router-dom";
import axios from "axios";

// let config = { Authorization: "3055f8f90fa44bbe8bda05385a20690a" };
// const baseurl = "https://newsapi.org/v2/top-headlines?sources=bbc-news";

const EventDetails = (props) => {
  const { state } = useLocation();

  if (!state) return null;

  // const [title, setTitle] = useState("");

  // const { eventName } = useParams();

  // useEffect(() => {
  //   axios
  //     .get(`${baseurl}`, { headers: config })
  //     .then((response) => setTitle(response.data));
  // }, []);

  // useEffect(() => {
  //   const neweventName = baseurl.find(
  //     (eventNames) => eventNames.eventName === parseInt(eventName)
  //   );
  //   setTitle(neweventName.title);
  // }, []);

  return (
    <div>
      <Navbar />
      <div className={styles.eventBg}>
        <div className="container">
          <div>
            <img
              src={DetailsImage}
              alt="ticket"
              width="100%"
              className={styles.heroEventImage}
            />
          </div>
          <div className={styles.bookingDetails}>
            <div className={styles.nameBook}>
              <div>
                <div className={styles.eventNameHeader}>
                  <h1 className={styles.eventName}> {props.title}</h1>
                </div>
                <div className={styles.genre}>
                  <div className={styles.genreText}>{props.author}</div>
                </div>
              </div>
              <div className={styles.bookingBtn}>
                <div className={styles.booking}>
                  <Link to="/GeneralBooking">
                    <button
                      className={styles.bookBtn}
                      style={{ height: "60px", fontSize: "18px" }}
                    >
                      Book
                    </button>
                  </Link>
                </div>
              </div>
            </div>
            <div className={styles.venueTime}>
              <div className={styles.dateTime}>
                <div className={styles.dateTimeText}>{props.author}</div>
                <div className={styles.price}>{props.author}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default EventDetails;

//App.js

import "./App.css";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Home from "./components/Home/Home";
import EventDetails from "./components/EventDetails/EventDetails";
import GeneralBooking from "./components/GeneralBooking/GeneralBooking";
import AllotedSeated from "./components/AllotedSeated/AllotedSeated";
import Checkout from "./components/Checkout/Checkout";

function App() {
  return (
    <BrowserRouter>
      <div className="App">
        <Switch>
          <Route path="/" exact>
            <Home />
          </Route>
          <Route path="/:title" exact children={<EventDetails />}></Route>
          <Route path="/GeneralBooking" exact>
            <GeneralBooking />
          </Route>
        </Switch>

        {/* <EventDetails /> */}
        {/* <GeneralBooking /> */}
        {/* <AllotedSeated /> */}
        {/* <Checkout /> */}
      </div>
    </BrowserRouter>
  );
}

export default App;

解决方案

Since it doesn't appear as though you've stored the posts state sufficiently high enough in the ReactTree to be accessible by component on other routes I suggest using route state to send a specific post object to a receiving route.

Event - Update the Link to send also the post object.

<Link
  to={{
    pathname: `/${post.title}`,
    state: { post },
  }}
>
  <button type="button" className={styles.btns}>{post.author}</button>
</Link>

EventDetails - Use the useLocation hook to access the route state.

import { useLocation } from "react-router-dom";

const EventDetails = (props) => {
  const { state } = useLocation();

  if (!state.post) return null;

  return (
    // ...render all the post fields available from state.post
    // i.e. state.post.title
  );
};

这篇关于React 路由器 - 单击卡片并使用 useParams 和 reacthooks 重定向到包含该卡片内容(卡片详细信息)的新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆