【问题标题】:How to pass info with React Router to the new page?如何使用 React Router 将信息传递到新页面?
【发布时间】:2020-04-14 20:50:47
【问题描述】:
我已经做了一个我所追求的快速 CodeSandBox 示例。我在登录页面上有一个“我们的课程”部分,带有“阅读更多”按钮。单击“阅读更多”按钮后,根据课程,它将呈现该信息。现在我让按钮工作,但现在我被卡住了,无法弄清楚如何将相关信息传递到重定向页面。现在假设我想让课程“标题”和“描述”传递到重定向页面。我该怎么做?
CodeSandBox 链接在这里 - Link here
【问题讨论】:
标签:
javascript
reactjs
react-router
react-router-dom
【解决方案1】:
您的 CardInfo 组件可以从您的课程存储库中查找课程详细信息。
要执行查找,您可以使用 react-router useParams 挂钩确定选择了哪张卡;这使您可以确定通过所选路线传递的课程标识符,即
import React from "react";
import courses from "./courses";
import { useParams } from "react-router-dom";
const CardInfo = () => {
const { id } = useParams();
const course = courses.find(course => course.id === id);
return (
<div>
<h1>{course.title}</h1>
<p>{course.description}</p>
</div>
);
};
export default CardInfo;
可以看到一个完整的工作示例here(它是您的 CodeSandBox 的一个分支)。
【解决方案2】:
您可以使用Link 组件的to 属性的对象版本在路由之间传递数据,因此将您的Link 组件更改为:
//Card.jsx
<Link
to={{
pathname: `/card/${course.title}`,
state: {
description: course.description
}
}}>
<button className="btn">Read more</button>
</Link>
然后在您的CardInfo.jsx 组件中,您可以通过props.location.state.description 访问此数据
import React from "react";
const CardInfo = (props) => {
console.log(props)
return (
<div>
<h1>
How can I pass course title here depending on which button I click
</h1>
<p>{props.location.state.description}</p>
</div>
);
};
export default CardInfo;
希望对你有帮助:)
【解决方案3】:
在CardInfo 组件中,您可以使用react-router-dom 库中的useParams 访问路由提供的id。
我正在使用您的<Route path="/card/:id" component={CardInfo} /> 作为参考。
这样实现:
import React from 'react'
import { useParams } from 'react-router-dom'
const CardInfo = () => {
const { id } = useParams()
return <div>Card ID: {id}</div>
}
export default CardInfo
现在您已经获得了id,您应该可以将它用于您需要的任何东西。
【解决方案4】:
有多种方法可以传递这些数据:
您可以像这样通过链接状态传递数据:
<Link
to={{
pathname: `/card/${course.title}`,
state: { description: course.description }
}}
>...</Link>
然后像这样在 CardInfo 组件中读取它:
import { useLocation } from "react-router-dom";
const CardInfo = () => {
const location = useLocation();
console.log(location.state) // { description: 'Lorem ipsum...' }
但是,最好的方法是在 URL 中传递课程 ID,然后从 course.js 文件中读取其余信息:
这已经是正确的,您接受课程 ID 作为 URL 参数:
<Route path="/card/:id" component={CardInfo} />
在链接中传递课程 ID:
<Link to={`/card/${course.id}`}>
从 URL 中读取 id 参数,并从课程文件中获取其余课程信息:
import { useParams } from "react-router-dom";
import courses from './courses'
const CardInfo = () => {
const params = useParams();
console.log(courses[params.id]);