【问题标题】:How to catch the dynamic part of the URL in react router如何在反应路由器中捕获 URL 的动态部分
【发布时间】:2021-01-31 22:09:03
【问题描述】:

我有这条路线调用PriceWithId 函数

<Route path='/collections/:pId' component={PriceWithID} />

函数是这样的

const PriceWithID = ({match}) =>
    {
        let test = Object.entries(match);
        let test2 = test.filter(([prop])=>(prop === 'params'));
        let test3 = test2[0][1];
        let test4 = Object.values(test3)[0]
        return(
          <Price image={IMGS.filter((i)=>(i.id === parseInt(test4,10)))[0]}/>
        );
    }

我知道有一种更好的单线方式来实现test4。我使用的方法经过反复试验。谁能告诉我更好的方法,以便我可以用它替换 parseInt 中的 test4

【问题讨论】:

    标签: javascript html reactjs react-router react-router-dom


    【解决方案1】:

    使用this.props.match.params.pId

    或带有功能组件

    const PriceWithID = (props) =>
        {
            let pId = props.match.params.pId
            return(
              <Price image={IMGS.filter((i)=>(i.id === parseInt(pId))[0]}/>
            );
        }
    

    【讨论】:

    • 感谢@Burning Alcohol
    【解决方案2】:

    可以通过这种方式改进之前的答案:

    const PriceWithID = ({match}) =>
        {
            return(
              <Price image={IMGS.filter((i)=>(i.id === parseInt(match.params.pId,10)))[0]}/>
            );
        }

    但由于之前的解决方案是正确的,我将其标记为答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-30
      • 2021-12-25
      • 2021-02-05
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多