【问题标题】:Passing data to routes将数据传递给路由
【发布时间】: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


【解决方案1】:

为什么不呢?

<Link to={`/better_to_have_prefix/${project.name}/${project}/${project.index}`}>
   Open project
</Link>

路线中的某处

&lt;Route path="/better_to_have_prefix/:paramProjectName/:paramProject/:paramIndex" component={MyProject} /&gt;

最后在组件“MyProject”中的某个地方

this.props.match.params.paramProjectName
this.props.match.params.paramProject
this.props.match.params.paramIndex

【讨论】:

  • 看来project 是一个对象,而不是一个字符串,所以这个解决方案非常行不通。
  • 是的,我明白了,但是如果有愿望))) 并没有那么多参数,可以用类似的方式完成...看起来很糟糕...最好使用redux
  • 从我得到的答案来看,全球状态管理似乎是最好的方法。谢谢
猜你喜欢
  • 2015-10-15
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 2017-02-28
  • 2019-11-05
  • 1970-01-01
  • 2023-03-20
  • 2022-01-17
相关资源
最近更新 更多