使用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>
在我的应用程序中,我有一个动态导航栏,我想放在那里,它可以用来选择不同的生成组件(由/search
中Content
组件中的操作生成(。我的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
组件中,我尝试使用访问数据
const {state} : any = useLocation();
const {setLock,setLotsQuery} : any = state;
这导致Uncaught TypeError: Cannot destructure property 'setLock' of 'state' as it is null.
我知道不能直接序列化函数。我应该如何重新评估路由数据的方式?
到目前为止,层次结构看起来像
App
-Nav (child component)
-Content(search subroute)
-Component(nextComp subroute)
数据在Content
中输入,然后发送到应用程序(这是当前能够设置功能的问题(。数据由App
处理,然后传递给导航并生成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>