如何使用 React router v6 将参数传递到链接中? [英] How to pass params into link using React router v6?

查看:169
本文介绍了如何使用 React router v6 将参数传递到链接中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的主要部分类,其中保留了所有链接的路由

export default class Section extends React.Component {使成为() {返回 (<div style={{backgroundColor:"white"}}><路线><路由路径="/";element={<Home/>}/><路由路径=/discover"元素={<发现/>}/><路线路径="/shop/makeup";元素={<化妆/>}/><路由路径="/home/:id";element={<DetailsPage/>}/></路线>

)}}

这是我的卡片页面,它从上下文中获取数据.

从'react'导入React;从 './CardData.js' 导入 {DataContext};从 'react-router-dom' 导入 {Link}导入'../App.css';导出默认类 HomeCard 扩展 React.Component {静态上下文类型 = 数据上下文;使成为(){const {products} = this.context;返回 (<div><div className="卡片">{ products.map((val,index)=>{返回(<div className="卡片"键={val.id}><卡片样式={{ width: '14rem' }} className=cardhead"><Card.Img 变体=顶部"src={val.imgsrc} className=cardimg"/><卡片体><卡片.文本>{val.mname}</卡片文本><卡片

从这里我使用 LINK 将 val.id 传递给页面的 url

 <Button className="overlay";变体=主要的">{/* <a style={{color:"white"}} href={props.link} className=card-link">View</a>*/}查看</链接><Card.Text><strong>{val.price}</strong></卡片文本><卡片文本><strong>{val.id}</strong></卡片文本></卡片页脚></Card.Body></卡片>

);

)}}

我想将链接网址访问到我的产品的详细信息页面,如下所示:

导出默认类DetailsPage extends React.Component {静态上下文类型 = 数据上下文;状态 = {产品: []}getProduct = () =>{如果(this.props.match.params.id){const res = this.context.products;const data = res.filter(item =>{返回 item.id === this.props.match.params.id})this.setState({产品:数据})}};componentDidMount(){this.getProduct();}使成为() {const {product} = this.state;const {addCart} = this.context;返回 (<>{product.map(item =>(<div className="详细信息";键={item.id}><img src={item.imgsrc} alt="/><div className="box"><div className="row"><h2>{item.mname}</h2><span>${item.price}</span>

<链接到=/购物车"className =购物车"onClick={() =>addCart(item.id)}>添加到购物车</链接>

))} </>) }}

不幸的是,它给出了一个错误,说 TypeError: Cannot read property 'params' of undefined

解决方案

问题

  1. react-router-dom v6 Route 通过 element 属性渲染的组件不接收 路由道具.
  2. 路由子组件必须使用react钩子访问路由上下文,即useParamsuseLocationuseHistory 等...因此必须是功能组件.
  3. 不再存在 withRouter 高阶组件.

解决方案

DetailsPage 是一个基于类的组件,我看到有几个选项可以访问路由的匹配参数.

  1. DetailsPage 转换为功能组件并使用 useParams 反应钩子.
  2. 编写您自己的 withRouter HOC 以访问路由上下文并将任何 react-hook 可访问值作为 props 传递.

我不会介绍将基于类的组件转换为功能性组件,但可以提供一个简单的 HOC 解决方案来传递给 DetailsPage(或任何其他基于类的组件) 匹配参数.

const withRouter = WrappedComponent =>道具 =>{const params = useParams();//等等...其他 react-router-dom v6 钩子返回 (<包裹组件{...道具}参数={参数}//等等.../>);};

您现在可以包装 &以非常熟悉的方式导出基于类的组件,它们来自 v4/v5.

v6 api-reference

This is my main section class where all routes to the links is kept

export default class Section extends React.Component {
    render() {
        return (
            <div style={{backgroundColor:"white"}}>
                   <Routes>
                   <Route path="/"  element={<Home/>} />
                    <Route path="/discover" element={<Discover/>}   />
                    <Route path="/shop/makeup" element={<Makeup/>}  />
                    <Route path="/home/:id" element={<DetailsPage/>}  />
                    </Routes>
            </div>
        )}}

This is my card page which is getting data from the context.

import React from 'react';
import {DataContext} from './CardData.js';
import {Link} from 'react-router-dom'
import '../App.css';
export default class HomeCard extends React.Component {
    static contextType = DataContext;
    render(){
        const {products} = this.context;
  return (
    <div>
      <div className="card">
                { products.map((val,index)=>{
                   return(
                    <div className="card" key={val.id}>
                    <Card style={{ width: '14rem' }}  className="cardhead">
  <Card.Img variant="top" src={val.imgsrc} className="cardimg"/>
  <Card.Body>
    <Card.Text>{val.mname}
    </Card.Text>
    <Card

From here i had passed the val.id to the url of the page using LINK

    <Link to={`/home/${val.id}`}>
    <Button className="overlay" variant="primary">
      {/* <a  style={{color:"white"}} href={props.link} className="card-link">View</a> */}
      View</Button> </Link>
    <Card.Text><strong>{val.price}</strong>
    </Card.Text>
    <Card.Text><strong>{val.id}</strong>
    </Card.Text>
    </Card.Footer>
  </Card.Body>
</Card>
</div>);                
    </div>
  )}}

I want to access the the link url into the details page of my product which is as follows :

export default class DetailsPage extends React.Component {
    static contextType = DataContext;
    state = {
        product: []
    }
    getProduct = () =>{
        if(this.props.match.params.id){
            const res = this.context.products;
            const data = res.filter(item =>{
                return item.id === this.props.match.params.id
            })
            this.setState({product: data})
        }};
    componentDidMount(){
        this.getProduct();
    }
    render() {
        const {product} = this.state;
        const {addCart} = this.context;
        return (
            <>
                {product.map(item =>(
                        <div className="details" key={item.id}>
                            <img src={item.imgsrc} alt=""/>
                            <div className="box">
                                <div className="row">
                                    <h2>{item.mname}</h2>
                                    <span>${item.price}</span>
                                </div>
                                <Link to="/cart" className="cart" onClick={() => addCart(item.id)}>
                                    Add to cart
                                </Link>
                            </div>   </div>  ))} </> )  }}

Unfortunately it is giving an error saying TypeError: Cannot read property 'params' of undefined

解决方案

Issue(s)

  1. react-router-dom v6 Route components rendered via the element prop don't receive route props.
  2. Route children components must use react hooks to access the route context, i.e. useParams, useLocation, useHistory, etc... and therefore must be functional components.
  3. There no longer exists a withRouter Higher Order Component.

Solution

DetailsPage is a class-based component do I see a couple options for getting access to the route's match params.

  1. Convert DetailsPage to be a functional component and use the useParams react hook.
  2. Write your own withRouter HOC to access the route context and pass as props any of the react-hook accessible values.

I won't cover converting a class-based component to a functional component, but can provide a simple HOC solution to pass to DetailsPage (or any other class-based component) the match params.

const withRouter = WrappedComponent => props => {
  const params = useParams();
  // etc... other react-router-dom v6 hooks

  return (
    <WrappedComponent
      {...props}
      params={params}
      // etc...
    />
  );
};

You can now wrap & export your class-based components in the very familiar way they were from v4/v5.

v6 api-reference

这篇关于如何使用 React router v6 将参数传递到链接中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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