如何在react中导航到另一个功能组件并传递值



我想从仪表板中的用户列表中传递一个特定的用户id。我有一个按钮,叫做扩展,当我点击这个按钮,它会带我到另一个页面,将显示我所有的用户信息和详细信息。

我试图通过用户的id,以便能够从我的DB中获取指定用户的信息

当我单击扩展按钮到CustomerProfile页面时,我正在从CustomersList页面移动。

但是在第二页,我得到的值是undefined

我代码:

const CustomerList = () => {
const navigate = useNavigate();
const [data, setData] = useState([]);
const [id, setID] = useState("");
const list = []
useEffect(() => {
firebase.firestore().collection("Users").get().then((userSnapshot) => {
userSnapshot.forEach((doc) => {

const {powerAccount,first_name,registerDate,email,company,country,phone} = doc.data();
list.push({
usersID:doc.id,
powerAccount:powerAccount,
first_name:first_name,
registerDate:registerDate,
email:email,
company:company,
country:country,
phone:phone,
});

})
setData(list);
console.log(list)
})

},[]);
return (
<Button
color="primary"
variant="contained"
onClick={()=>{
navigate('/app/CustomerDetails', { state: { id: data.usersID } });//this is how i am navigating and passing the value
}}
>
Expand
</Button>
)

第二页:

const CustomerProfile = (props) => {
const {state} = useLocation();
const { id } = state; // Read values passed on state
console.log(id)//here i get this log as undefined
const [name,setName] = useState("");
useEffect(() => {
firebase.firestore().collection("Users").doc(id).get().then((userSnapshot) => {
console.log(userSnapshot.data())// here i get this log as undefined
})

},[]);
}

我做错了什么?

编辑:

这是我的routes.js文件:

const routes = [
{
path: 'app',
element: <DashboardLayout />,
children: [
{ path: 'account', element: <Account /> },
{ path: 'customers', element: <CustomerList /> },
{ path: 'CustomerDetails', element: <CustomerDetails /> },
{ path: 'ReportDetails', element: <ReportDetails /> },
{ path: 'report', element: <ReportList /> },
{ path: 'freight', element: <FreightList /> },
{ path: 'dashboard', element: <Dashboard /> },
{ path: 'analytics', element: <Analytics /> },
{ path: 'products', element: <ProductList /> },
{ path: 'settings', element: <Settings /> },
{ path: '*', element: <Navigate to="/404" /> }
]
},
{
path: '/',
element: <MainLayout />,
children: [
{ path: 'login', element: <Login /> },
{ path: 'register', element: <Register /> },
// { path: '404', element: <NotFound /> },
{ path: '/', element: <Navigate to="/login" /> },
{ path: '*', element: <Navigate to="/app/dashboard" /> }
]
}
];

如果你正在使用React>16.8.0和功能组件,React Router>5.1.0中有一个新的useHistory钩子。你的路由是这样传递id的。

<Switch>
<Route exact path="/form" component={Form} />
<Route exact path="/data/:id" component={Formdata} />
</Switch>

然后从你想要的地方使用useHistory钩子从react-router-dom。

const HandleSubmit = (e) => {
e.preventDefault();
history.push(`/data/${initstate}`);
};

最后在你想要id的地方使用useParms钩子来获取id:

let params = useParams();
setUserID(params.id);

相关内容

  • 没有找到相关文章

最新更新