假设我有一条路径如下:

const runWhenRouteIs123 = () => {}

<Routes>
  <Route path="123" element={<div>hello</div>} />
  ... // other routes
<Routes>

我想让功能runWhenRouteIs123()在路由为"WhateverIsBeprere/123"的时候运行.该函数使用Reaction Redux来分派一些逻辑. 在此之前,使用render()进行渲染是可能的,render()允许预先运行逻辑.短路判断不会对我起作用,因为会抛出一条警告:"当呈现另一个组件时,无法更新组件".

我之前try 过,但收到了上面的警告:

<Routes>
  <Route path="123" element={dispatch(xyz()) && <div>hello</div>} />
  ... // other routes
<Routes>

如果需要更多的澄清,请让我知道!

推荐答案

您可以使用useMatch来计算是否存在当前匹配的路由,并将runWhenRouteIs123函数作为副作用运行.如果存在匹配项,则useMatch返回Match对象,否则返回NULL.

import {
  Routes,
  Route,
  useMatch,
} from 'react-router-dom';

...

const isRoute123 = useMatch("/123");

useEffect(() => {
  const runWhenRouteIs123 = () => {};

  if (isRoute123) {
    runWhenRouteIs123();
  }
}, [isRoute123]);


<Routes>
  <Route path="123" element={<div>hello</div>} />
  ... // other routes
<Routes>

或者,您可以将runWhenRouteIs123向下移动到已布线的组件,并在挂载时从useEffect挂钩调用.

示例:

const Component123 = () => {
  useEffect(() => {
    runWhenRouteIs123();
  }, []);

  return <div>hello</div>;
}
<Routes>
  <Route path="123" element={<Component123 />} />
  ... // other routes
<Routes>

Reactjs相关问答推荐

如何将google地址lat收件箱设置为输入值?

如何使用react-router-dom导航到网页中的其他路由?

如何通过浏览器路由在单独的.jsx文件中使用MUI抽屉?

根据另一个Select中的选定值更改Select中的值

React Router:在没有手动页面刷新的情况下,路由不会更新内容

使用Next.js和Next-intl重写区域设置

MUI 日期 Select 器 - 最小日期混乱

如何删除 bootstrap 手风琴上的边框

当我无法引用模态组件时,如何使模态组件在 Next.js/React 中管理自己的状态?

在React中使用if条件时如何更改Tailwind中元素的文本 colored颜色

useEffect 内的 onClick 和 addEventListener 之间的 click 事件顺序差异

useEffect内部的RETURN语句在首次按钮点击事件中似乎无效的原因是什么?

在MongoDB中,如何获取最后N条记录中字段不为空或不为空字符串的数据

Spring Boot + React + MySQL应用的架构层面有哪些?

将 ref 转发到所有页面(路由组件)只是为了将其应用于
并具有跳过导航链接(按钮).有没有更好的办法?

在 redux 中分派到另一个减少时状态值不会改变

如何禁用来自 React Native API 的某些特定项目的可touch 不透明度

react-markdown 不渲染 Markdown

ReactJS:按钮启用禁用更改 colored颜色

我可以在类组件中使用 useState 挂钩吗?