如何从 v6 中的 Route 调用函数

DOR*_*ITO 6 reactjs react-router react-router-dom

以前,在react-router-dom v5(或更低版本)中,您可以使用:

<Route path="/" render={() => {doSomething(); return <ComponentName />}} />

既可以触发函数又可以创建路由,而无需在 ComponentName 组件内部创建任何额外的代码。render在 v6 中被替换为,element现在如何实现这一点?

Dre*_*ese 8

react-router-domv6 中,不再有任何 props 来渲染 中的函数Route,而是存在element采用 JSX 文字的 props。创建一个发出副作用的包装器组件,并将您正在路由上渲染的组件包装起来。在 React 中使用useEffect钩子是为了避免无意的副作用。

const DoSomethingWrapper = ({ children }) => {
  useEffect(() => {
    doSomething();
  }, []);
  return children;
};
Run Code Online (Sandbox Code Playgroud)

...

<Route
  path="/"
  element={(
    <DoSomethingWrapper>
      <ComponentName />
    </DoSomethingWrapper>
  )}
/>
Run Code Online (Sandbox Code Playgroud)


DOR*_*ITO 1

这是我想出的答案:

const doSomething = (arg1, component) => {
  //posting arg1 as an example of whatever you are wanting to do.
  console.log(arg1);
  return component;
};
Run Code Online (Sandbox Code Playgroud)
<Route path="/" element={doSomething("string", <Home />)} />
Run Code Online (Sandbox Code Playgroud)

编辑*将其标记为答案,因为它与原始问题中的代码最相似,但这并不是唯一正确的答案。请考虑其他很好的答案,这可能更合适,具体取决于您的需求。