react 18.2与react-router-dom 6.3配合使用 我有这种风格的路由.

<Routes>
        <Route path="/" element = {<App/>}>
             <Route path="search" element = {<Content/>} />
             <Route path="nextComp/:id" element = {<Component/>} />
        </Route>
</Routes>

在我的应用程序中,我有一个动态导航栏,我想用它来 Select 不同的生成组件(由/searchContent组件中的操作生成).在我的App组件中,有一些状态需要由Content组件设置.我向下传递信息的内容大致如下:

const App: React.FC = () => {
    const [lock, setLock] = useState<Boolean>(false);
    const [lotsQuery, setLotsQuery] = useState<lotWaferQueryInput[]>([]);

    const navigate = useNavigate();
    const onClickHandle(() => {
        navigate('/search', {state: { 
            setLock : setLock,
            setLotsQuery: setLotsQuery
        }});
    }, []);
}

在我的Content组件中,我try 使用以下命令访问数据:

const {state} : any = useLocation();
const {setLock,setLotsQuery} : any = state;

这将导致 Uncaught TypeError: Cannot destructure property 'setLock' of 'state' as it is null.我知道你不能直接序列化一个函数.我应该如何重新处理我路由数据的方式?

到目前为止,层次 struct 看起来像是

App
-Nav (child component)
-Content(search subroute)
-Component(nextComp subroute)

Content中录入数据,然后发送到App(这是当前能够设置功能的问题).数据由App处理,然后传递到NAV并生成Component(子路由)

那么,我如何实现从子路由组件向父路由发送数据?如有任何建议,欢迎光临.

推荐答案

路由状态需要是JSON可序列化的,因此发送函数将不起作用.我建议通过Outlet的上下文和useOutletContext钩子将函数向下公开到嵌套的路径.

示例:

import { Outlet } from 'react-router-dom';

const App: React.FC = () => {
  const [lock, setLock] = useState<Boolean>(false);
  const [lotsQuery, setLotsQuery] = useState<lotWaferQueryInput[]>([]);

  ...

  return (
    ...
      <Outlet context={{ setLock, setLotsQuery }} />
    ...
  );
};

在嵌套布线的组件中:

import { useOutletContext } from 'react-router-dom';

...

const { setLock, setLotsQuery } = useOutletContext();

...

<Routes>
  <Route path="/" element={<App />}> // <-- provides context value
    <Route path="search" element={<Content />} /> // <-- can access context value
    <Route path="nextComp/:id" element={<Component />} />
  </Route>
</Routes>

Reactjs相关问答推荐

有正确的方法来设置我的金牛座应用程序的图标吗?

React onKeyUp不一致地使用快速Shift+键按压

如何在react组件中使用formik进行验证

替换谷歌 map api默认信息窗口与自定义

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

使用REACT-RUTER-V6和ZUSTANDreact 中的身份验证

React组件未出现

如何修复ReferenceError:在构建过程中未定义导航器

React 无效的钩子调用:如何避免嵌套钩子?

如何解决使用react-hook-form和yup动态创建的输入不集中的问题

Mui 在 TextField 标签上添加工具提示显示两个工具提示框

React中useAuthenticator的authState在成功登录后仍保持未认证状态 - 需要强制刷新

React:如何使用条件渲染和react 挂钩来更新另一个组件的状态?

在按钮单击中将动态参数传递给 React Query

在 Nextjs13 应用程序目录中呈现从 supabase 获取的数据

基于标记名的博客详细信息分组没有发生

在嵌套的 Stack Navigator 中的 BottomTabBar 中导航会导致比以前更多的渲染

用 scss 覆盖 MUI

当状态改变时如何执行一些动作,但只针对第一次更新?

试图将页面限制为仅登录但有条件的用户似乎永远不会运行