[英]How to pass props within components with react-router v6
I'm struggling to pass props between components with react-rouer v6我正在努力通过react-rouer v6在组件之间传递道具
Here is the routes in App.tsx, I want to pass props from the component (Home) which redirect to this one (EditUser)这是 App.tsx 中的路由,我想从组件 (Home) 传递道具,重定向到这个 (EditUser)
<Routes>
<Route path={ROUTES.HOME} element={<Home />} />
<Route path={ROUTES.EDIT_USER} element={<EditUser props />} />
</Routes>
The home page have some functionality to render a table with users主页有一些功能来呈现一个包含用户的表格
Here is the function to navigate to the EditUser page to be able to edit这是 function 导航到 EditUser 页面以便能够编辑
I want to be able to pass one of the users once the button "edit" is clicked (I added the state since I read that was the way to acces from the Edit User page)单击“编辑”按钮后,我希望能够通过其中一个用户(我添加了 state,因为我读到这是从“编辑用户”页面访问的方式)
const handleEdit = (user: IUser) => {
navigate(ROUTES.EDIT_USER, {
state: {
user,
},
});
};
The edit button (Redirection is working It's just the fact to pass that user from components)编辑按钮(重定向有效这只是从组件传递该用户的事实)
<EditButton
data-testid={`edit-button-${user.id}`}
text={ES.common.edit}
onClick={() => {
handleEdit(user);
}}
></EditButton>
Any idea?任何的想法?
As always, thank you!一如既往,谢谢!
When you send state in the route transition it isn't sent via props, but rather it's sent via the routing context.当您在路由转换中发送 state 时,它不是通过 props 发送的,而是通过路由上下文发送的。 In the EditUser
component you can access the sent route state via the location
object returned from the useLocation
hook.在EditUser
组件中,您可以通过useLocation
挂钩返回的location
object 访问已发送的路由 state。
Example:例子:
import { useLocation } from 'react-router-dom';
...
const location = useLocation();
const { state } = location;
const { user } = state || {};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.