【发布时间】:2022-01-13 18:00:40
【问题描述】:
是否可以使用 useLocation 中的状态将对象数据(一些包含不太大数组的数据)传递给动态路由?如果不是,那么如何在路由之间传递数据(在全局父组件中无法访问数据)。
// A project component that lists some projects
const Projects = () => {
const data = {someData}
return (
projects ?
<section className="grid my-5 grid-cols-1 gap-4 lg:gap-10 lg:grid-cols-2">
{projects.map((project) =>
<ProjectCard key={project.index} project={project}/>
)}
</section>
: <h1>Nothing to see here</h1>
)
// A project card containing some details and a link to open the project in a different route, i want the route to have access to the project data of the project that was clicked
const ProjectCard = ({project}) => {
return (
<div>
<p> Some project details here </p>
<Link
to={`/${project.name}`}
state={project}
id={project.index}>
Open project
</Link>
</div>
)
}
【问题讨论】:
-
这看起来很糟糕。你没有
redux或至少useContext吗? -
可以接受吗?当然,这是固执己见,但它会起作用。如果您没有任何全局状态,即Lifting State Up、React Context、redux 等...(此时您可能应该考虑它)并简单地将 id 或引用传递给它那么选项是有限的:要么按照你的要求以路由状态发送它,要么序列化并在 queryString 中参数化的 URL 中发送。
-
感谢 Fer 和 Drew,我认为此时最好设置全局状态管理。正如您所指出的,使用查询字符串。你会推荐哪个 useContext 或 redux?
标签: reactjs react-router