【问题标题】:How can I set dynamically the number for useNavigation hook?如何动态设置 useNavigation 挂钩的数量?
【发布时间】:2021-12-28 14:36:23
【问题描述】:

我正在尝试编写一个 react Breadcrumbs 组件,该组件会自动设置在 react-router-dom 中返回导航所需的数字。

我有一个带有路径名的数组,它的长度可以是 2 或更多。所有项目都是链接,除了最后一个步骤之外,还可以返回多个步骤

users(往后两页)/name(往前一页)/type(inactive)

我决定在 react-router-dom 中使用 useNavigation 钩子返回。

// This is my array, for instance
const pathnames = ['users', 'name', 'type'];

所以我需要一个看起来像这样的函数/方法。

pathTokens.map((item, index, arr) => {
 if (item !== arr[arr.length - 1]) {
   return <BreadcrumbsItem action ={() => navigate(numberOfStepsBack)} content={item}/>
 } else {
   return <BreadcrumbsItem content={item}/>
 }
});

【问题讨论】:

  • 您是在寻找findIndex 函数,还是您的问题还有更多?
  • @samuei,问题是对于navigate 和公共循环索引(对于循环

标签: javascript reactjs react-router-dom


【解决方案1】:

如果我正确理解您的问题,您想计算每个面包屑片段允许的后退导航数。

给定:

  • const pathnames = ['users', 'name', 'type'];
  • users(返回两页,-2)/name(返回上一页,-1)/type(无效,0)

使用公式index + 1 - pathnames.length 计算每个映射的面包屑片段的后退导航数。

Segment index equation: index + 1 - pathnames.length goBack
users 0 0 + 1 - 3 -2
name 1 1 + 1 - 3 -1
type 2 2 + 1 - 3 0

应用于你的映射函数:

pathTokens.map((item, index, arr) => {
  const numberOfStepsBack = index + 1 - arr.length;
  const action = () => navigate(numberOfStepsBack);
  return (
    <BreadcrumbsItem
      {...numberOfStepsBack ? { action } : {}}
      content={item}
    />
  );
});

【讨论】:

  • 上帝感谢你,这行得通。但如果对你来说不难的话,你能解释一下为什么要在 index 值上加 1 吗?
  • @Wells +1 来自应用数学。该公式以index - (array.length - 1) 开头,或者更确切地说是index + -1 * (array.length - 1),当您分发-1 时,结果为index - array.length + 1。从这里我只是重新排列了术语,因为加法是可交换的。 ??‍♂️ 换句话说,index + -length + 1 === index + 1 + -length
猜你喜欢
  • 2021-02-11
  • 2020-05-19
  • 1970-01-01
  • 2022-01-23
  • 2022-01-16
  • 1970-01-01
  • 2022-06-27
  • 2019-11-27
  • 2021-05-24
相关资源
最近更新 更多