根据对象中的值动态更改 React 应用程序中的 URL

Dynamically altering URL in react app based on values in object

我正在尝试用对象的值替换 url 的参数,前提是参数与对象中的值相同。

我知道了,所以它会替换值,但它只是创建一个包含 2 个项目的数组,我希望基本上将它们“合并”在一起以创建一个 URL。

非常感谢任何帮助!

其中 urlData 包含正在传入的类似内容:

[
    {
        param: ':userId',
        value: userId || '',
    },
    { param: ':messageId', value: messageId || '' }
]

我的菜单是这样的:

{menu?.map((menuItem, index) => {
    const { title, path } = menuItem
    const finalPath = urlData?.map(
        (url, index) =>
            path.includes(url?.param)
                ? path.replace(
                    url?.param,
                    url?.value
                  )
                : path
        )

    console.log('final', finalPath)

    return (
        <Link
            to={finalPath}
            key={index}
            className={
                pathname === finalPath ||
                finalPath.includes(pathname)
                    ? 'active'
                    : ''
            }
        >
            {title}
        </Link>
    )
})}

我目前的回复:

[
    "/app/messages/be493d77/:messageId",
    "/app/messages/:userId/2cd4df7d"
]

我在找什么:

    "/app/messages/be493d77/2cd4df7d"

与其映射 urlData 数组以生成等长数组,不如减少数组。

示例:

const userId = "be493d77";
const messageId = "2cd4df7d";

const path = "/app/messages/:userId/:messageId";

const urlData = [
  { param: ":userId", value: userId || "" },
  { param: ":messageId", value: messageId || "" }
];

const finalPath = urlData.reduce(
  (path, { param, value }) => path.replace(param, value),
  path
);

console.log(finalPath);

或者,您可以使用 react-router-dom 中的 generatePath 实用程序。这需要 urlData param 值来匹配参数名称而不是路径的字符串文字。

示例:

import { generatePath } from "react-router-dom";

const urlData = [
  { param: "userId", value: userId || "" },
  { param: "messageId", value: messageId || "" }
];

const finalPath = generatePath(
  path,
  urlData.reduce(
    (params, { param, value }) => ({
      ...params,
      [param]: value
    }),
    {}
  )
);